Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase Storage Image upload – Function to return the Image URL after uploading it

I need to implement this async function,

const uploadImage = async () => {
  const filename = new Date().getTime() + photo!.name
  const storage = getStorage(app)
  const storageRef = ref(storage, filename)
  const uploadTask = uploadBytesResumable(storageRef, photo!);
  
  uploadTask.on('state_changed',
    (snapshot) => {},
    (error) => {
      console.log("error while uploading photo", error)
    },
    async () => {
      photoUrl = await getDownloadURL(uploadTask.snapshot.ref);
      console.log("getDownloadURL", photoUrl)
      return photoUrl
    }
  );
}

It is the function to upload images to Firebase-Storage. Here I need to return the "photoUrl ". I need to call the function like,

const res = await uploadImage(photo)

how do I do this? The uploaded image’s URL should return from the function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The object returned by uploadBytesResumable is also a promise, so you can just await that and then call getDownloadURL:

const uploadImage = async () => {
  const filename = new Date().getTime() + photo!.name
  const storage = getStorage(app)
  const storageRef = ref(storage, filename)
  const uploadTask = uploadBytesResumable(storageRef, photo!);
  await uploadTask;
  photoUrl = await getDownloadURL(uploadTask.snapshot.ref);
  return photoUrl
}

You actually don’t even need a reference to the task, as you already have the storageRef, the above can be shorted to:

const uploadImage = async () => {
  const filename = new Date().getTime() + photo!.name
  const storage = getStorage(app)
  const storageRef = ref(storage, filename)
  await uploadBytesResumable(storageRef, photo!);
  return await getDownloadURL(storageRef);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading