Search code examples
javascriptfirebaseasync-awaitfirebase-storage

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.


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);
    }