gpt4 book ai didi

javascript - 如何在Firebase存储触发功能中获取公共(public)下载链接: "onFinalize"?

转载 作者:行者123 更新时间:2023-12-02 20:05:23 26 4
gpt4 key购买 nike

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

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

});

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

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

因此,它们不是公共(public)链接。如何在此触发函数中获取公共(public)下载链接?

最佳答案

您必须使用异步 getSignedUrl() 方法,请参阅 Cloud Storage Node.js 库的文档:https://cloud.google.com/nodejs/docs/reference/storage/2.0.x/File#getSignedUrl .

所以下面的代码应该可以解决问题:

.....
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 function get download url after successfully save image to firebase cloud storage .

关于javascript - 如何在Firebase存储触发功能中获取公共(public)下载链接: "onFinalize"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53189911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com