Reputation: 55
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.
Upvotes: 1
Views: 975
Reputation: 533
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)
Upvotes: 1
Reputation: 598688
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);
}
Upvotes: 5