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

查看:12
本文介绍了如何在 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) => {

});

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 库的文档:https://cloud.google.com/nodejs/docs/reference/storage/2.0.x/File#getSignedUrl.

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 Question &回答 firebase 函数成功后获取下载地址将图像保存到 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天全站免登陆