【问题标题】:return the download URL of a file uploaded to firebase返回上传到 firebase 的文件的下载 URL
【发布时间】:2018-05-21 20:07:14
【问题描述】:

有没有一种简单的方法来获取上传到 Firebase 的文件的下载 URL?

(我尝试过使用上传函数返回的快照,但找不到任何东西......)

     fileref.put(file).then(function(snapshot){
     self.addEntry(snapshot);   
     ///  return snapshot.url???
     });

【问题讨论】:

    标签: javascript firebase firebase-storage snapshot


    【解决方案1】:

    Yamil 引用的文档 - Firebase javascript SDK file upload - 建议使用快照的 ref 属性来调用 getDownloadURL 方法,该方法返回包含下载链接的承诺:

    以您的代码为起点:

    fileref.put(file)
       .then(snapshot => {
           return snapshot.ref.getDownloadURL();   // Will return a promise with the download link
       })
    
       .then(downloadURL => {
          console.log(`Successfully uploaded file and got download link - ${downloadURL}`);
          return downloadURL;
       })
    
       .catch(error => {
          // Use to signal error if something goes wrong.
          console.log(`Failed to upload file and get link - ${error}`);
       });
    

    我知道这似乎是不必要的努力,您应该能够通过快照的属性获取链接,但这是 Firebase 团队的建议 - 他们可能有充分的理由这样做。

    【讨论】:

      【解决方案2】:

      要从快照中获取默认创建的 Url,您可以使用downloadURL,即snapshot.downloadURL

      请记住始终使用.on('state_changed')Documentation here 跟踪上传进度。

      【讨论】:

      • 此处引用的文档使用函数snapshot.ref.getDownloadURL().then(downloadURL) 来获取对下载 URL 的引用,它不只是访问快照对象上的属性。
      • snapshot.downloadURL 已弃用,请改用 snapshot.ref.getDownloadURL()
      【解决方案3】:

      使用给定in official docs的基于用户的安全规则时

      // 只有单个用户可以写入“他们的”图像

        match /{userId}/{imageId} {
          allow write: if request.auth.uid == userId;
        }
      

      snapshot.downloadURL 检索到的 url 暴露了 userId。如何克服这种安全风险。

      【讨论】:

      • 如果您正确编写存储和数据库安全规则,则不会有暴露用户 ID 的风险。此外,这应该是另一个问题(我相信它已经存在),而不是作为不同问题下的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2012-03-14
      • 1970-01-01
      • 2020-05-24
      • 2018-12-28
      • 2020-01-29
      相关资源
      最近更新 更多