如何将Firebase存储映像url保存到Firebase数据库



如何在Firebase数据库中保存上传到Firebase存储的图像的url?

当下面的代码运行时,我得到了这个错误:

未捕获(承诺中(FirebaseError:函数DocumentReference.set((调用时使用了无效数据。不支持的字段值:未定义(在文档用户/HNJr68ZYXJXbA7v9n2jSHscXwSp1中的字段pfpURL中找到(在新ui(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:176225Gf(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:176376Fr(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,

})
})
})
});

您在回调中第二次调用getDownloadURL(),这将用promise替换正确的下载URL。

解决方案是重用传递到then():中的url

storageRef.getDownloadURL().then(function(url) {
document.querySelector('#profile-picture').src = url;
db.collection('users').doc(uid).set({
pfpURL: url,
})
})

最新更新