Reputation: 106
I'm trying to store all the user's profile photos in the realtime database, but I'm stucked with a problem.
When trying to upload the PhotoUrl with this code, this error shows up.
Code:
var user = firebase.auth().currentUser;
user.updateProfile({
// Here, "name" and "imgUrl" are parameters of parent function.
// I don't think this is the reason, but if it helps,
// "imgUrl" always come from a <img> src.
displayName: name,
photoUrl: imgUrl
}).then(function(){
// Here is where I try to upload all to the database
firebase.database().ref("/Usuarios/" + user.uid).set({
"email": email,
"name": name,
"photoUri": user.photoUrl, // This is where I think the problem originates.
"uid": user.uid // This calls user again, and it works perfectly.
});
});
Error:
Uncaught Error: Firebase.set failed: First argument contains undefined in property 'Usuarios.kD1tD1NAmsaGiW0zj6lFz9GDWro1.photoUri'.
When I do alert(user.photoUrl), it shows as 'undefined'.
The first thing I thought was that it can't be saved in database because it isn't a String, so I tried calling toString() from it, but I can't.
toString() error:
Uncaught TypeError: Cannot read property 'toString' of undefined
So, how can I save the photoUrl from a user (as String) in Firebase Database?
Thanks in advance.
Upvotes: 6
Views: 11896
Reputation: 106
For most I tried not to do this type of workarounds, ended up uploading the photo to Firebase Storage, then setting User.photoURL and "photoUri" DB field to the url of the uploaded image:
user = firebase.auth().currentUser;
avatarStgRef = firebase.storage().ref("Usuarios/" + user.uid + "/avatar.jpg");
// imgFile the Photo File.
avatarStgRef.put(imgFile).then(function(snapshot){
snapshot.ref.getDownloadURL().then(function(url){ // Now I can use url
user.updateProfile({
photoURL: url // <- URL from uploaded photo.
}).then(function(){
firebase.database().ref("Usuarios/" + user.uid).set({
"photoUri": url // <- URL from uploaded photo.
});
});
});
});
Upvotes: 3