【问题标题】:Firebase Storage Image upload - Function to return the Image URL after uploading itFirebase Storage 图片上传 - 上传后返回图片 URL 的功能
【发布时间】:2023-02-08 22:00:34
【问题描述】:
我需要实现这个异步功能,
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 的功能。这里我需要返回“photoUrl”。我需要像这样调用函数,
const res = await uploadImage(photo)
我该怎么做呢?上传的图像的 URL 应该从函数返回。
【问题讨论】:
标签:
javascript
firebase
async-await
firebase-storage
【解决方案1】:
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);
}
【解决方案2】:
将多个文件上传到 firebase 并返回它们的 URL 是一样的
async function uploadMultipleFilesToFirebase(imagesArray) {
try {
const requests = imagesArray.map(async (imageFile) => {
const storageRef = ref(storage, filename)
const uploadTask = uploadBytesResumable(storageRef, imageFile)
await uploadBytesResumable(storageRef, imageFile);
return await getDownloadURL(storageRef);
})
return Promise.all(requests)
} catch (error) {
throw({ error })
}
}
然后使用它:
urlsOfUploadedImages.value = await uploadProductToFirebase(productData)