How do i get download URL once upload is done on firebase storage

I want to get the download URL once image upload is finished and then the downloadURL is set to my newAds.picLink( , but in this code since upload is in progress

newAds.update({ picLink: downloadURL });

is called which throws an error since downloadURL is currently not available and under progress. I have resolved this by using setTimeOut to 8 sec which lets the image to upload completely first and then downloadURL is recieved but that's not correct.

How can i create a correct callback that sets newAds.picLink = downloadURL once image is completely uploaded?

 addSubmitted.addEventListener('click', e => {
 const newAds = _db.ref(userID).push();
 const newAd = {

const ref =;
const file = $('#exampleInputFile').get(0).files[0];
const name = (+new Date() + '-' +;
const task = ref.child(name).put(file, {contentType: file.type});

function abc() {
    task.snapshot.ref.getDownloadURL().then((downloadURL) => {
        console.log('File available at', downloadURL);
        newAds.update({ picLink: downloadURL });

    task.catch(error => {
        // Use to signal error if something goes wrong.
        console.log(`Failed to upload file and get link - ${error}`);




From the Firebase documentation on uploading a file:

var uploadTask = storageRef.child('images/rivers.jpg').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
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case // or 'paused'
      console.log('Upload is paused');
    case // or 'running'
      console.log('Upload is running');
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL:
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('File available at', downloadURL);

So this registers a state_changed observer. When the upload has completed, this calls StorageReference.getDownloadURL() to get the download URL.


put() returns an UploadTask, which you can use like a normal promise, because it declares a then() method:

const task = ref.child(name).put(file, {contentType: file.type});
task.then(snapshot => {


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.