Firebase用户上传和个人资料照片

时间:2016-12-19 00:50:17

标签: javascript firebase firebase-storage

您好寻求帮助,

我目前有一些JavaScript代码,允许已登录的用户将图像上传到Firebase存储。我希望他们上传的图片是他们的个人资料图片,但我似乎无法将上传的图片链接回特定用户?

它有效,我可以在控制台中看到上传的图像,但没有任何内容可以识别用户上传的内容。

//Upload Profile Picture 
//Altered code from: Firebase Youtube Channel. 

      //Get Elements
      var uploader = document.getElementById('uploader');
      var fileButton = document.getElementById('fileButton');

      //Listen for file 
      fileButton.addEventListener('change', function(e){

         //Get File
         var file = e.target.files[0];


         //Create a Storage Ref
         var storageRef = firebase.storage().ref('profilePictures/' + file.name);

         //Upload file
         var task = storageRef.put(file);

         var user = firebase.auth().currentUser;        

         //Update Progress Bar 
         task.on('state_changed', 

         function progress(snapshot){
            var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) *100;
            uploader.value = percentage;

            //if percentage = 100
            //$(".overlay").hide();         
         },

         function error(err){

         },

         function complete(){

         }

       );           
    });


//Display Profile Picture   

function showUserDetails(){

   var user = firebase.auth().currentUser;
   var name, photoUrl;

   if (user != null) {
      name = user.displayName;
      photoUrl = user.photoURL;

      document.getElementById('dp').innerHTML=photoURL;
      document.getElementById('username').innerHTML=name;  
}}

我在Firebase文档中看到了以下代码,但我不了解如何更新照片网址图片或显示它。

var user = firebase.auth().currentUser;
var name, email, photoUrl, uid;

if (user != null) {
   name = user.displayName;
   email = user.email;
   photoUrl = user.photoURL;
   uid = user.uid; // The user's ID, unique to the Firebase project. Do NOT use
    // this value to authenticate with your backend server, if
    // you have one. Use User.getToken() instead.
}

非常感谢您提供任何帮助或建议。

1 个答案:

答案 0 :(得分:13)

您希望按用户名存储文件:

// Get current username
var user = firebase.auth().currentUser;

// Create a Storage Ref w/ username
var storageRef = firebase.storage().ref(user + '/profilePicture/' + file.name);

// Upload file
var task = storageRef.put(file);

因此,如果用户为user:12345且文件名为profile.jpg,则该文件将另存为user:12345/profilePicture/profile.jpg。您可以使用Security Rules保护此项,如下所示:

service firebase.storage {
  match /b/<your-firebase-storage-bucket>/o {
    match /{userId}/profilePicture/{fileName} {
      // Anyone can read
      allow read;
      // Only the user can upload their own profile picture
      // Profile picture must be of content-type "image/*"
      allow write: if request.auth.uid == userId
                   && request.resource.contentType.matches('image/.+');
    }
  }
}