前提・実現したいこと
React + firebaseで画像アップロードとダウンロードの処理を書いています。
一括表示をしたいため、この記事にあるように、storageに保存したurlをdatabaseに保存することにより一覧表示をしたいと考えています。
発生している問題・エラーメッセージ
しかし、firebaseのアクセス権限の関係から、storageに保存したファイルのURLを見ると、?alt=mediaの後に&token?={トークン}が必要となっていました。そこで該当トークンを得ようと思ったのですが、得る方法を見つけることができませんでした。
ファイルURLのtoken?=以下の情報を取得するにはどうすれば良いのでしょうか?
該当のソースコード
storageにある画像ファイルのurlをdatabaseに保存する処理
js
1// storageのurlをdatabaseに保存 2const getImageUrl = async () => { 3 const currentUser = await firebase.auth().currentUser; 4 const imageDb = await firebase.firestore(); 5 const bucketName = await 'sample'; 6 const filePath = await `users/${currentUser.displayName}/images`; 7 const idToken= await currentUser.getIdToken(true); 8 console.log('token', idToken); // これでは無い 9 try { 10 imageDb 11 .collection('users') 12 .doc(currentUser.displayName) 13 .collection('images') 14 .add({ 15 downLoadUrl: `https://firebasestorage.googleapis.com/v0/b/${bucketName}.appspot.com/o/${encodeURIComponent( 16 filePath, 17 )}?alt=media&token=${idToken}`, // idTokenが違う 18 }); 19 console.log('set url'); 20 } catch (err) { 21 console.log(err); 22 } 23 };
試したこと
このトークンをfirebase.auth().currentUser.getIdToken(true)(参考:ID トークンの確認)を使って呼び出そうと思った所、全く異なるトークンが表示されてしまいました。
補足情報(FW/ツールのバージョンなど)
firebase cloud fire storeを使用
データ保存は以下のように書いています。
user名/images直下にファイルが保存されるようになっています。
js
1// storageにデータ保存 2const saveImage = async (inputFile) => { 3 const db = await firebase.storage().ref(); 4 const currentUser = await firebase.auth().currentUser; 5 try { 6 const imageRef = await db.child(`${currentUser.displayName}/images`); 7 const res = await imageRef.put(inputFile); 8 await getImageUrl(); 9 console.log(res); 10 } catch (err) { 11 console.log(err); 12 } 13 };
あなたの回答
tips
プレビュー