繁体   English   中英

如何将Firebase存储镜像url保存到firebase数据库中?

[英]How to save Firebase Storage image url to firebase database?

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

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

未捕获(承诺)FirebaseError:Function DocumentReference.set() 使用无效数据调用。 不支持的字段值:未定义(在文档 users/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: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在 od.set ( https : //www.gstatic.com/firebasejs/7.17.1/firebase-fir estore.js:1:263206 )

HTML:

<div>
   <img id="profile-picture">
</div>

记者:

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() ,它将正确的下载 URL 替换为 promise。

解决方案是重用传递给then()url

storageRef.getDownloadURL().then(function(url) {
    document.querySelector('#profile-picture').src = url;

    db.collection('users').doc(uid).set({
        pfpURL: url,
    })
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM