Firebase get Download URL after successful image upload to firebase storage

Viewed 23209

I am trying to upload a single image to Firebase Storage, then grab its download url and assign this to a variable.

I can upload my image to firebase successfully, however I cannot retrieve the download url. here is what I have tried already.

upload() {
    let storageRef = firebase.storage().ref();
    let success = false;

    for (let selectedFile of [(<HTMLInputElement>document.getElementById('file')).files[0]]) {
      let router = this.router;
      let af = this.af;
      let folder = this.folder;
      let path = `/${this.folder}/${selectedFile.name}`;
      var iRef = storageRef.child(path);
      iRef.put(selectedFile).then((snapshot) => {
        console.log('Uploaded a blob or file! Now storing the reference at', `/${this.folder}/images/`);
        af.list(`/${folder}/images/`).push({ path: path, filename: selectedFile.name })
      });
    }

    // This part does not work
    iRef.getDownloadURL().then((url) => {this.image = url});
    console.log('IREF IS ' + iRef)
    console.log('IMAGEURL IS ' + this.image)

  }

The Console logs are these:

    IREF IS gs://my-app-159520.appspot.com/images/Screen Shot 2017-08-14 at 12.19.01.png
    view-order.component.ts:134 IMAGEURL IS undefined
Uploaded a blob or file! Now storing the reference at /images/images/

I have been trying to use the iRef reference to grab the download url but I keep getting errors. I am trying to grab the url so I can assign it to the this.image variable and then store it in my database using another function.

5 Answers

The API has changed. Use the following to get downloadURL

  snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log("File available at", downloadURL);
  });

In 2019, I gained access to the url of a newly-saved file in firebase with the following function:

const uploadImage = async(uri) => {
  const response = await fetch(uri);
  const blob = await response.blob();
  // child arg specifies the name of the image in firebase
  const ref = firebase.storage().ref().child(guid());
  ref.put(blob).then(snapshot => {
    snapshot.ref.getDownloadURL().then(url => {
      console.log(' * new url', url)
    })
  })
}

.put() function is returning a task, which can be used to track the uploading state.

For example you can listen for progress, error or completion like so:

onUploadImage () {
  const self = this
  const file = self.selectedFile
  if (!file) {
    return
  }
  self.isUploading = true
  const storageRef = firebase.storage().ref('/images/' + file.name)
  const task = storageRef.put(file)
  task.on('state_changed',
    function progress (snapshot) {
      self.status = 'UPLOADING...'
      self.percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
    },
    function error () {
      self.status = 'FAILED TRY AGAIN!'
      self.isUploading = false
    },

    function complete (event) {
      self.status = 'UPLOAD COMPLETED'
      self.isUploading = false
      storageRef.getDownloadURL().then((url) => { console.log(url) })
    }
  )
}

As of web version v9 (modular) you can achieve this in this way:

import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage"; 

uploadImage = () => {
  const storage = getStorage()
  const reference = ref(storage, 'file_name.jpg')
  const file = e.target.files[0]

  uploadBytes(reference, file)
    .then(snapshot => {
      return getDownloadURL(snapshot.ref)
    })
    .then(downloadURL => {
      console.log('Download URL', downloadURL)
    })
}
Related