如何在Firebase存储触发功能内获取公共下载链接:“ onFinalize”?

Osa*_*ama 4 firebase google-cloud-functions firebase-storage

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

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

});
Run Code Online (Sandbox Code Playgroud)

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

Anonymous caller does not have storage.objects.get access to ... {filename}
Run Code Online (Sandbox Code Playgroud)

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

Ren*_*nec 6

您必须使用异步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;
    })

});
Run Code Online (Sandbox Code Playgroud)

请注意,要使用该getSignedUrl()方法,您需要使用专用服务帐户的凭据来初始化Admin SDK,请参阅成功将映像成功保存到Firebase云存储后,此SO Question&Answer firebase函数获取下载网址

  • 感谢您指出此错误,我已经编辑了答案。如果您认为我的答案有帮助,则可以对其进行投票并接受,请参阅https://stackoverflow.com/help/someone-answers。谢谢。 (2认同)

Inz*_*lik 6

*使用此功能:

function mediaLinkToDownloadableUrl(object) {
        var firstPartUrl = object.mediaLink.split("?")[0] // 'https://www.googleapis.com/download/storage/v1/b/abcbucket.appspot.com/o/songs%2Fsong1.mp3.mp3'
        var secondPartUrl = object.mediaLink.split("?")[1] // 'generation=123445678912345&alt=media'

        firstPartUrl = firstPartUrl.replace("https://www.googleapis.com/download/storage", "https://firebasestorage.googleapis.com")
        firstPartUrl = firstPartUrl.replace("v1", "v0")

        firstPartUrl += "?" + secondPartUrl.split("&")[1]; // 'alt=media'
        firstPartUrl += "&token=" + object.metadata.firebaseStorageDownloadTokens

        return firstPartUrl
    }
Run Code Online (Sandbox Code Playgroud)

您的代码可能如下所示:

export const onAddSong = functions.storage.object().onFinalize((object) => {

    console.log("object: ", object);

    var url = mediaLinkToDownloadableUrl(object);

    //do anything with url, like send via email or save it in your database in playlist table 
    //in my case I'm saving it in mongodb database

    return new playlistModel({
        name: storyName,
        mp3Url: url,
        ownerEmail: ownerEmail
    })
    .save() // I'm doing nothing on save complete
    .catch(e => {
        console.log(e) // log if error occur in database write
    })

})
Run Code Online (Sandbox Code Playgroud)

*我已经在 mp3 文件上测试了这种方法,我确定它适用于所有类型的文件,但如果它对您不起作用,只需转到 firebase 存储仪表板打开任何文件并复制下载 url,然后尝试生成相同的url 在你的代码中,如果可能的话也编辑这个答案