Firebase 存储图片上传 - 上传后 return 图片 URL 的功能

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

我需要实现这个异步函数,

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

上传图片到Firebase-Storage的功能。这里我需要return“photoUrl”。我需要像这样调用函数,

const res = await uploadImage(photo)

我该怎么做?上传图片的 URL 应该 return 来自函数。

uploadBytesResumable 返回的对象也是一个 promise,所以你可以 await 然后调用 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
}

实际上你甚至不需要对任务的引用,因为你已经有了 storageRef,上面可以简写为:

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