I’m trying to upload a video with identifiers. So the goal is to upload the videos to firebase storage whilst saving the identifiers to firestore, but i keep getting this error.
ERROR Error getting download URL: [FirebaseError: Firebase Storage: Object ‘Sermon/1705503121152’ does not exist. (storage/object-not-found)]
heres my code
async function handleUpload() {
if (videoFile) {
await upload(videoFile);
} else {
alert("Please select a video first.");
}
}
async function upload(uri) {
const response = await fetch(uri);
const blob = await response.blob();
const storageRef = ref(storage, "Sermon/" + new Date().getTime());
const uploadTask = uploadBytesResumable(storageRef, blob);
uploadTask.on("state_changed", (snapshot) => {
// Handle upload progress if needed
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log(`Upload progress: ${progress}%`);
if (snapshot.state === "paused") {
console.log("Upload paused");
} else if (snapshot.state === "running") {
console.log("Upload running");
if (progress === 100) {
console.log("Upload completed");
handleUploadSuccess(uploadTask);
}
}
});
}
async function handleUploadSuccess(uploadTask) {
try {
const downloadUrl = await getDownloadURL(uploadTask.snapshot.ref);
await saveRecord(
downloadUrl,
title,
preacher,
series,
new Date().getTime()
);
setVideoFile("");
} catch (error) {
console.error("Error getting download URL:", error);
}
}
async function saveRecord(url, title, preacher, series, createdAt) {
try {
const docRef = await addDoc(collection(db, "sermon"), {
url,
title,
preacher,
series,
createdAt,
isFeatured: '0'
});
console.log("file saved", docRef.id);
} catch (e) {
console.log(e);
}
}
2
Answers
It seems that you’re calling
getDownloadURL
on a non-existing reference, or before the file upload has completed on the server.I recommend simplifying the code and using the fact that
uploadTask
is a promise, so you can await it:I also typically don’t use
uploadTask.snapshot.ref
, but usestorageRef
instead.Your code might be trying to get a download URL before the upload is complete. The object doesn’t exist in storage until the upload finishes.
Instead of using
snapshot.state === "running"
andprogress === 100
to determine completion, you should use the pattern shown in the example in the documentation, which I have redacted here to make it more clear where completion is fully known:Read the comments to see where successful upload is known – it’s in the third callback function parameter to
on()
, which you are currently not using.Also consider reviewing the API documentation for UploadTask.on to better understand how it works. Specifically: