Reputation: 3949
I am using firebase to upload a photo of a user into the database, I use expo image picker in combination, and here is the code:
const handleImagePicked = async (pickerResult) => {
console.log("here");
if (!pickerResult.cancelled) {
setImage(pickerResult.uri);
const result = await uploadImageAsync(pickerResult.uri);
if (result) {
console.log("success");
return;
}
alert("Upload failed, sorry :(");
}
};
async function uploadImageAsync(uri) {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
const ref = firebase
.storage()
.ref(uid)
.child("/profile_pictures/" + uid);
const snapshot = await ref.put(blob);
blob.close();
const userRef = db.collection("users").doc(uid);
const res = await userRef.update({ photo: snapshot });
return await snapshot.ref.getDownloadURL();
}
this works correctly and I am able to see in my firebase under storage a new folder is created and inside the there is the image users have uploaded.
to retrieve the image on a different screen this is what I do:
let imageRef = firebase.storage().ref(userId);
imageRef
.getDownloadURL()
.then((url) => {
setImage({ profileImageUrl: url });
})
.catch((e) =>
console.log("getting downloadURL of image error => ", e)
);
but however, when I visit my profile page it doesn't show the image since it tells me there is an error:
getting downloadURL of image error => [FirebaseError: Firebase Storage: Object 'userId' does not exist. (storage/object-not-found)]
what am I doing wrong here?
Upvotes: 0
Views: 120
Reputation: 598623
The error message says that no file exists in the location you call getDownloadURL
on. From looking at the code, that makes sense.
You upload the image to:
firebase
.storage()
.ref(uid)
.child("/profile_pictures/" + uid);
You try to get the download URL from:
firebase.storage().ref(userId);
Those are two different locations. The first points to /$uid/profile_pictures/$uid
, while the second just points to /$uid
. You should use a reference to the same path in both places, and my recommendation would be to use for both:
firebase
.storage()
.ref("/profile_pictures/" + uid);
Upvotes: 1