firestoreに画像保存する方法調べてもfirebase storageの情報ばかり出てきて苦労したのでメモ。
やりたいこと :
firebase auth のTwitterプロバイダーから取得したTwitterアイコンURLから、画像をbase64形式に変換してfirestoreに保存する。言語はTypeScriptで書く。
では早速
URLを受け取ってbase64形式のstringを返すコード
// 画像をbase64形式のstringに変換
const getImageBase64 = async (url: RequestInfo | null) => {
if (url === null) return '';
const response = await fetch(url);
const contentType = response.headers.get('content-type');
const arrayBuffer = await response.arrayBuffer();
const APPLY_MAX = 1024;
let encodedStr = '';
// ArrayBufferの中身を1024バイトに区切って文字列にしていく
for (let i: number = 0; i < arrayBuffer.byteLength; i += APPLY_MAX) {
encodedStr += String.fromCharCode.apply(null, [...new Uint8Array(arrayBuffer.slice(i, i + APPLY_MAX))]);
}
let base64String = window.btoa(encodedStr);
return `data:${contentType};base64,${base64String}`;
};
もしかすると下記のエラーが出ます。
Type 'Uint8Array' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
その場合は、tsconfig.jsonに以下を追加
{
"compilerOptions": {
"downlevelIteration": true
}
}
あとはfirestoreにstringフィールドとして保存したら完了です。
const icon: string = await getImageBase64(auth.currentUser.photoURL);
setDoc(doc(db, 'users', authUser.uid),{
userName: auth.currentUser.displayName,
userPhoto: icon,
});
以上。