return 下载 URL 上传到 firebase 的文件

return the download URL of a file uploaded to firebase

有没有一种简单的方法可以下载 URL 上传到 Firebase 的文件?

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

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

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

请记住使用 .on('state_changed')Documentation here

始终跟踪上传进度

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

// 只有个人用户可以写入 "their" 图像

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

url 检索到的 snapshot.downloadURL 公开了用户 ID。如何克服这种安全风险。

Yamil 引用的文档 - Firebase javascript SDK file upload - 建议使用快照的 ref 属性 调用 getDownloadURL 方法,其中 returns 一个承诺包含下载 link:

以您的代码为起点:

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

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