1

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.

2 Answers 2

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here is same thing to upload multiple files to firebase and return their URLs

  async function uploadMultipleFilesToFirebase(imagesArray) {
    try {
      const requests = imagesArray.map(async (imageFile) => {
        const storageRef = ref(storage, filename)
        await uploadBytesResumable(storageRef, imageFile);
        return await getDownloadURL(storageRef);
      })

      return Promise.all(requests)
    } catch (error) {
      throw({ error })
    }
  }

And then use it with:

urlsOfUploadedImages.value = await uploadProductToFirebase(productData)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.