首页 > 解决方案 > 通过从 Firebase 存储访问来更新用户的 photoURL

问题描述

我正在使用此 javascript 代码将图像上传到 firebase 存储,然后我想将此图像 url 更新为用户的 photoURL (firebase auth)

const fileButton = document.querySelector('#fileButton');
var imageURL;

fileButton.addEventListener('change', function(e) {
    //get file 
    var file = e.target.files[0];
    //create a storage reference
    var storageRef = storage.ref('profilePictures/' + userUID + '.jpg');
    //upload file
    var task = storageRef.put(file);
    //update progress bar
    task.on('state_changed',
        function progress(snapshot){

        },
        function error(err) {

        },
        function complete(){
            storageRef.getDownloadURL().then(function(url) {
                console.log(url);
                imageURL = url;
            })
            .catch(function(error) {
                // Handle any errors
                console.log(error);
            });
            // window.location.replace('/profile');
            var user = auth.currentUser;
            user.updateProfile({
                photoURL: imageURL
            })
            .then(function() {
                // Update successful.
                console.log(user);
            })
            .catch(function(error) {
                // An error happened.
                console.log(error);
            });
        }
    );
});

存储上的图像上传成功 ,但用户数据中的 photoURL不成功

uid: "t2TbJS6ut7NZH4UU8HeAVarGPOw2"
displayName: "Sachin Kumar"
photoURL: null
email: "s@gmail.com"
emailVerified: false

我做错了什么

标签: javascriptfirebase-authenticationfirebase-storage

解决方案


您需要等待storageRef.getDownloadURL()完成才能将其传递给user.updateProfile喜欢:

function complete() {
  storageRef.getDownloadURL().then(function(url) {
      console.log(url);
      imageURL = url;

      // Now you have valid `imageURL` from async call
      var user = auth.currentUser;
      user.updateProfile({ photoURL: imageURL })
        .then(function() { console.log(user) })
        .catch(function(error) { console.log(error) });

    })
    .catch(function(error) { console.log(error) });    
}

推荐阅读