【问题标题】:firebase storage file name changefirebase 存储文件名更改
【发布时间】:2020-03-26 07:33:43
【问题描述】:

我是 firebase 和 Javascript 的新手。
如何将文件名更改为用户的 uid 并将其保存到存储中? 我想在注册成功后上传一个文件。我应该在 createUserWithEmailAndPassword 还是 onAuthStateChanged 中编写函数?

function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var file = evt.target.files[0];

    var metadata = {
      'contentType': file.type
    };

    var storage_ref = storage.ref();

    storage_ref.child('userImages/' + user.uid).put(file, metadata).then(function(snapshot) {

      snapshot.ref.getDownloadURL().then(function(url) {
        console.log('File available at', url);
        profile_url = url;

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

      console.error('Upload failed:', error);

    });



  } // handleFileSelect

  document.getElementById('input_img').addEventListener('change',handleFileSelect, false);

【问题讨论】:

    标签: javascript firebase firebase-authentication firebase-storage


    【解决方案1】:

    您不能直接更改文件名。但是有一种间接的方法可以做到这一点,请查看question

    您希望用户的 UID 作为文件名,但您不会在 createUserWithEmailAndPassword 中得到它,因此您需要将该逻辑添加到 onAuthStateChanged 方法中。但是onAuthStateChanged 每次用户登录时都会被调用,因此您需要构建某种逻辑来仅在用户第一次登录时执行文件上传方法。

    【讨论】:

      【解决方案2】:

      要对正在创建的用户帐户采取行动,您可以使用then

      比如:

      function handleFileSelect(evt) {
        evt.stopPropagation();
        evt.preventDefault();
      
        firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // ...    
        }.then(function(credential) {
          var user = credential.user
      
          var file = evt.target.files[0];
      
          var metadata = {
            'contentType': file.type
          };
      
          var storage_ref = storage.ref();
      
          storage_ref.child('userImages/' + user.uid).put(file, metadata).then(function(snapshot) {
      
            snapshot.ref.getDownloadURL().then(function(url) {
              ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-11
        • 1970-01-01
        • 2016-11-05
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多