如何在Firebase数据库中保存上传到Firebase存储的图像的URL?
下面的代码运行时,出现此错误:
未捕获(已承诺)FirebaseError:函数DocumentReference.set()调用了无效数据。不支持的字段值:未定义(在文档用户/ HNJr68ZYXJXbA7v9n2jSHscXwSp1中的pfpURL字段中找到) 在新用户界面(https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:52471) 在$ f(https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:177580) 在Uf.ea(https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:172230) 在https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:176225 在Gf(https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:176263) 在https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:176376 在Fr(https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:45658) 在Bf(https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:176351) 在Mf(https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:173339) 在od.set(https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js:1:263206)
HTML:
<div>
<img id="profile-picture">
</div>
JS:
firebase.auth().onAuthStateChanged(function(user) {
var uid = firebase.auth().currentUser.uid
var fileButton = document.getElementById('choose-pfp');
fileButton.addEventListener('change', function(e) {
var storageRef = firebase.storage().ref("profile_pictures/" + uid);
var file = e.target.files[0];
storageRef.put(file).then(function(snapshot) {
window.alert("Profile picture has been uploaded!");
storageRef.getDownloadURL().then(function(url) {
document.querySelector('#profile-picture').src = url;
var url = storageRef.getDownloadURL();
db.collection('users').doc(uid).set({
pfpURL: url.value,
})
})
})
});
答案 0 :(得分:0)
您正在回调中第二次调用getDownloadURL()
,这将用promise替换正确的下载URL。
解决方案是重用传递到url
的{{1}}:
then()