7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

firebase-admin sdkでファイルのアップロードとダウンロードURLの取得

Posted at

firebase (client) SDKとやり方が違うのでメモ。

最初に知っておいたほうがいいこと

  • クライアントのSDKとはやり方(使える関数とか)が違う。
  • アップロードしたファイルがWeb Consoleのバグで閲覧できない(これでしばらくはまった)。
  • ダウンロードURLはStorageのパスそのままではなく、署名入りの専用URLを取得する必要がある
  • 返り値に含まれるmediaLinkでも閲覧はできるが、CGPの方でallUsersに閲覧権限を付与する必要がある(使わない)
  • vscodeが生成するリンクはゴミが入ってうまく表示されない(vscode依存)

実装

実装自体はなんら難しくありません。

index.js
const admin = require('firebase-admin');
admin.initializeApp({
    credential: admin.credential.cert("/path/to/key.json"),
    storageBucket: "xxxxxxxx.appspot.com",
});

const bucket = admin.storage().bucket();
const localFilePath = "./test.pdf";
const cloudFilePath = "docs/test.pdf";

const main = async () => {

    try {
    
        //upload
        const res = await bucket.upload(localFilePath, { destination: cloudFilePath, metadata: { contentType: "application/pdf" } });
        
        
        //get download url
        const url = await bucket.file(cloudFilePath).getSignedUrl({
            action: 'read',
            expires: '12-31-3020' //1000年後に設定
        });
        
        console.log(url);
        
    } catch (e) {
        console.log(e);
    }

}

main();

ダウンロードURLとして下記のようなものが生成されます。

[
  'https://storage.googleapis.com/test-fc01e.appspot.com/docs/test.pdf?GoogleAccessId=firebase-adminsdk-d9f6b%40test-fc01e.iam.gserviceaccount.com&Expires=33166249200&Signature=mi7v8aF7j%2FJSmfgszijUDlIF9dW0PNe3hd4fAPs7rqjja5yMV8ClKZgKj%2BAMhatNdQIscz2306%2BF7uMyXxP8dJgjKGuJHJowgs28R1zq%2FnMy3D5iQGUEitJWdmpebO6C87EALVh1b8JE5nB6BKsv0NKp9%2FFHLq3epTP01z6S68%2BPSXXwZz4HlSBwLOjUMPvrNLUf%2B80dCgrh5pjKQKJm6VAIUQmTpE8RBk4qQLiQKvU5gy8e8F2yzS%2BA1kV9cM8C%2F3ARJE9HGe%2FxBTFCBynbpliPc09YuhTUcQlRPnlYpeTklAmPq9%2BK1XFINs0mUs5534mzifHR0TAGuUN%2BLRrVqjw%3D%3D'
]
7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?