最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - return the download URL of a file uploaded to firebase - Stack Overflow

programmeradmin1浏览0评论

Is there a simple way to get the download URL of a file uploaded to Firebase?

(I've tried playing around with the snapshot returned by my upload function and couldn't find anything...)

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

Is there a simple way to get the download URL of a file uploaded to Firebase?

(I've tried playing around with the snapshot returned by my upload function and couldn't find anything...)

     fileref.put(file).then(function(snapshot){
     self.addEntry(snapshot);   
     ///  return snapshot.url???
     });
Share Improve this question edited May 11, 2017 at 9:24 David J. asked May 11, 2017 at 9:06 David J.David J. 1,91313 gold badges52 silver badges100 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 22

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.

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.

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.

发布评论

评论列表(0)

  1. 暂无评论