如何在Firebase存储触发功能内获取公共下载链接:"onFinalize"? [英] How to get public download link within a firebase storage trigger function: "onFinalize"?

查看:54
本文介绍了如何在Firebase存储触发功能内获取公共下载链接:"onFinalize"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个firebase云功能,该功能记录最近上传的文件到实时数据库的下载链接:

I am writing a firebase cloud function that records the download link of a recentally uploaded file to real-time database:

exports.recordImage = functions.storage.object().onFinalize((object) => {

});

对象"使我可以访问两个变量"selfLink"和"mediaLink",但是当它们在浏览器中输入时,它们都将返回以下内容:

"object" gives me access to two variables "selfLink" and "mediaLink" but both of them when entered in a browser they return the following:

Anonymous caller does not have storage.objects.get access to ... {filename}

因此,它们不是公共链接.如何在此触发功能内获取公共下载链接?

So, they are not public links. How can I get the public download link within this trigger function?

推荐答案

您必须使用异步getSignedUrl()方法,请参阅Cloud Storage Node.js库的文档:

You have to use the asynchronous getSignedUrl() method, see the doc of the Cloud Storage Node.js library: https://cloud.google.com/nodejs/docs/reference/storage/2.0.x/File#getSignedUrl.

因此,以下代码可以解决问题:

So the following code should do the trick:

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

exports.recordImage = functions.storage.object().onFinalize(object => {    
  const bucket = defaultStorage.bucket();
  const file = bucket.file(object.name);

  const options = {
    action: 'read',
    expires: '03-17-2025'
  };

  // Get a signed URL for the file
  return file
    .getSignedUrl(options)
    .then(results => {
      const url = results[0];

      console.log(`The signed url for ${filename} is ${url}.`);
      return true;
    })

});

请注意,为了使用getSignedUrl()方法,您需要使用专用服务帐户的凭据来初始化Admin SDK,请参阅此SO问题与解答.回答 firebase函数在成功后获取下载URL将图像保存到Firebase云存储中.

Note that, in order to use the getSignedUrl() method, you need to initialize the Admin SDK with the credentials for a dedicated service account, see this SO Question & Answer firebase function get download url after successfully save image to firebase cloud storage.

这篇关于如何在Firebase存储触发功能内获取公共下载链接:"onFinalize"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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