I was able to get the downloadURL of the image but i need to save it to my realtime database. Please help. Here is the code that i tried.
const storageRef = sRef(storage, 'images/' 'announcement/');
const file_ann = document.getElementById("image_ann").files[0];
const name_ann = file_ann.name;
const metadata_ann = {
contentType: file_ann.type
}
const uploadAnnouncement = uploadBytesResumable(storageRef, file_ann, metadata_ann);
getDownloadURL(uploadAnnouncement.snapshot.ref).then((announcementURL) => {
console.log('File available at', announcementURL);
})
const announcementimg = document.getElementById("image_ann").value;
set(ref(database, 'page-content/' 'announcement/'), {
announcementimg: announcementURL,
})
.then(() => {
window.alert("Announcement Updated!");
})
.catch((error) => {
window.alert("Error!");
});
CodePudding user response:
Getting the download URL is (like most modern cloud API calls) an asynchronous operation. This means that any code that needs the announcementURL
has to be inside the then()
block that is called when that URL is available.
So:
getDownloadURL(uploadAnnouncement.snapshot.ref).then((announcementURL) => {
console.log('File available at', announcementURL);
const announcementimg = document.getElementById("image_ann").value;
set(ref(database, 'page-content/' 'announcement/'), {
announcementimg: announcementURL,
})
.then(() => {
window.alert("Announcement Updated!");
})
.catch((error) => {
window.alert("Error!");
});
})