如何在firebase存储触发函数中获取公共下载链接:“完成”?

fdx2calv  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(170)

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

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

});

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

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

所以,它们不是公共链接。我怎样才能在这个触发函数中获得公共下载链接?

1tu0hz3e

1tu0hz3e1#

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

bn31dyow

bn31dyow2#

  • 使用此功能:
function mediaLinkToDownloadableUrl(object) {
        var firstPartUrl = object.mediaLink.split("?")[0] // 'https://storage.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://storage.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存储 Jmeter 板打开任何文件并复制下载URL,并尝试在代码中生成相同的URL,如果可能的话,也编辑这个答案

相关问题