Firebase:使用管理员SDK存储图像

Yas*_*sir 2 firebase firebase-storage firebase-admin

我正在尝试将图像存储到Firebase存储中,我正在使用node.js。

import * as admin from 'firebase-admin';

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://xxx-app.firebaseio.com',
    storageBucket: 'xxxx-app.appspot.com'
});


function storeHeadShots(){

    const bucket = admin.storage().bucket();

    bucket.upload('./headshots/Acker.W.png', function(err, file){
        if (!err){
            console.log('file uploaded')
        } else {
            console.log('error uploading image: ', err)
        }
    });

}
storeHeadShots();
Run Code Online (Sandbox Code Playgroud)

现在,上面的方法可以正常工作,但是我在存储中有一个文件夹,users/并且在此文件夹中我正在存储图像。如何访问该文件夹

Ewa*_*nes 5

对于试图解决相同问题的任何人。

该示例取自此处的官方文档但未说明如何将文件放入文件夹。默认示例将文件放置在存储桶的根目录下,名称与本地文件相同。

我不得不在这里更深入地研究Cloud Storage类文档,发现对于存在options一个destination参数,该参数描述了存储桶中的文件。

在以下示例中,本地文件images/bar.png将被上传到默认存储桶的文件/foo/sub/bar.png

const bucket = admin.storage().bucket();

bucket.upload('images/bar.png', {
  destination: 'foo/sub/bar.png',

  gzip: true,
  metadata: {
    cacheControl: 'public, max-age=31536000'
  }
}).then(() => {
  console.log(`${filename} uploaded.`);
}).catch(err => {
  console.error('ERROR:', err);
});
Run Code Online (Sandbox Code Playgroud)

希望这可以为其他人节省一些时间。祝您上传愉快!

  • 如何从blob上传? (5认同)
  • 有没有办法在上传后获取下载地址? (2认同)