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

时间:2018-11-07 12:57:40

标签: firebase google-cloud-functions firebase-storage

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

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

});

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

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

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

*使用此功能:

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
    }

这是您的代码的外观:

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
    })

})

*我已经在mp3文件上测试了此方法,我确定它可以在所有类型的文件上使用,但是如果它对您不起作用,则只是转到Firebase存储信息中心,打开任何文件并复制下载网址,然后尝试在您的代码中生成相同的网址,并在可能的情况下也编辑此答案