从使用firebase-admin上传的文件中获取公共URL [英] Get Public URL from file uploaded with firebase-admin

查看:98
本文介绍了从使用firebase-admin上传的文件中获取公共URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用firebase-admin和firebase-functions将文件上传到Firebase存储中.

I use firebase-admin and firebase-functions to upload a file in Firebase Storage.

我在存储中有以下规则:

I have this rules in storage:

service firebase.storage {
  match /b/{bucket}/o {
    match /images {
      allow read;
      allow write: if false;
    }
  }
}

我想使用以下代码获取公共网址:

And I want get a public URL with this code:

const config = functions.config().firebase;
const firebase = admin.initializeApp(config);
const bucketRef = firebase.storage();

server.post('/upload', async (req, res) => {

  // UPLOAD FILE

  await stream.on('finish', async () => {
        const fileUrl = bucketRef
          .child(`images/${fileName}`)
          .getDownloadUrl()
          .getResult();
        return res.status(200).send(fileUrl);
      });
});

但是我有此错误.child is not a function. 如何使用firebase-admin获取文件的公共URL?

But I have this error .child is not a function. How can I get the public url of a file with firebase-admin?

推荐答案

来自

From the sample application code on the using Cloud Storage documentation, you should be able to implement the following code to obtain the public download URL after the upload is successful:

// Create a new blob in the bucket and upload the file data.
const blob = bucket.file(req.file.originalname);
const blobStream = blob.createWriteStream();

blobStream.on('finish', () => {
    // The public URL can be used to directly access the file via HTTP.
    const publicUrl = format(`https://storage.googleapis.com/${bucket.name}/${blob.name}`);
    res.status(200).send(publicUrl);
});

或者,如果您需要公开访问的下载URL,请参阅此答案,其中建议使用

Alternatively, if you need a publicly accessible download URL, see this answer which suggests using getSignedUrl() from the Cloud Storage NPM module because the Admin SDK doesn't support this directly:

您需要使用 @ google-cloud/storage NPM模块.

You'll need to generate a signed URL using getSignedURL via the @google-cloud/storage NPM module.

示例:

const gcs = require('@google-cloud/storage')({keyFilename: 'service-account.json'});
// ...
const bucket = gcs.bucket(bucket);
const file = bucket.file(fileName);
return file.getSignedUrl({
  action: 'read',
  expires: '03-09-2491'
}).then(signedUrls => {
  // signedUrls[0] contains the file's public URL
});

这篇关于从使用firebase-admin上传的文件中获取公共URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆