return the download URL of a file uploaded to firebase

[亡魂溺海] 提交于 2019-12-02 04:04:22

To get the Url created by default from the snapshot you can use downloadURL, meaning snapshot.downloadURL.

Remember to always keep tracking the progress of the upload by using .on('state_changed'), Documentation here.

The documentation referenced by Yamil - Firebase javascript SDK file upload - recommends using the snapshot's ref property to invoke the getDownloadURL method, which returns a promise containing the download link:

Using your code as a starting point:

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

I know it seems like unnecessary effort and that you should be able to get the link via a property of the snapshot, but this is what the Firebase team recommends - they probably have a good reason for doing it this way.

When using user based security rules as given in official docs

// Only an individual user can write to "their" images

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

url retrieved by snapshot.downloadURL is exposing userId. How to overcome this security risk.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!