Nikhil Raghavendra
Nikhil Raghavendra

Reputation: 117

getDownloadURL does not work correctly - Firebase Storage (Web)

The following code does not seem to log the download URL of the file that is being uploaded and gives me the following error.

GET ...{URL that is not the download URL}... 404()

This is my code.

     //Get image
     var file = a.target.files[0];

     //create a storage reference
     var storageRef = firebase.storage().ref('images/' + file.name);

     //store the image
     var task = storageRef.put(file);

     var storage = firebase.storage();
     storageRef.child('images/'+file.name).getDownloadURL().then(function(url) {
        console.log(url);          
      }).catch(function(error) {
        // Handle any errors
      });

So how do I get the downloadURL?

Upvotes: 0

Views: 3664

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Uploading the file is an asynchronous operation that may take some time to complete. Since your code is not handling that, you're retrieving the download URL when the file hasn't completed uploading yet.

From the documentation for uploading files to Firebase Storage comes this example:

// File or Blob, assume the file is called rivers.jpg
var file = ...

// Upload the file to the path 'images/rivers.jpg'
// We can use the 'name' property on the File API to get our file name
var uploadTask = storageRef.child('images/' + file.name).put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // See below for more detail
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  var downloadURL = uploadTask.snapshot.downloadURL;
});

You can see that this example gets the download URL after the upload has completed.

If you don't care about progress and failure, it can be as simple as:

uploadTask.on('state_changed', null, null, function() {
  var downloadURL = uploadTask.snapshot.downloadURL;
});

Upvotes: 3

Related Questions