くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

Cloud Storage for Firebaseのよく使うのまとめ(クライアント/Admin)

FirebaseのCloud Storage、とても便利だけど、
Web上で使うfirebaseとCloud Function上で使うfirebase-adminで若干操作が違う。。

よく調べなおすけど、毎回辿り着くのが大変なので、備忘用。

Webクライアント(firebase)

クライアント側での操作はこんな感じ。
ダウンロードは実態じゃなくダウンロードURLを取得する形。

import * as firebase from "firebase/app";
// 初期化は省略

const fileName:string = "...";
const file: File = //...

// storageのroot referenceを取得
const storageRef = firebase.storage().ref();

// アップロード先のreferenceを取得
const imagePath = `user/image/{fileName}`;
const imagesRef = storageRef.child(imagePath);


// ファイルをアップロード
const snapshot = await imagesRef.put(file);

// アップロードしたファイルのURLを取得
const imageURL = await snapshot.ref.getDownloadURL();

// ファイルの削除
await imagesRef.delete();

Admin(firebase-admin)

firebase-adminを使うときはこんな感じ。
Admin Cloud Storage APIGoogle Cloud Storage APIを使う形に。

bucketはCloud StrageのBucketなので、クライアントとは違う。

import * as admin from "firebase-admin";
// 初期化は省略

// アップロードするファイルのパス
const filePath:string = "...";

// bucketを取得
const bucket = admin.storage().bucket();

// アップロード先のパス
const uploadFilePath = `user/image/{fileName}`;

// ファイルのアップロード
await bucket.upload(filePath, { destination: uploadFilePath });

// ファイルのダウンロード
const downloadFilePath = 
await bucket.file(uploadFilePath).download({ destination: downloadFilePath });

// ファイルの削除
await bucket.file(uploadFilePath).delete();

以上!!