Firebase User Uploads and Profile Pictures

imconnor picture imconnor · Dec 19, 2016 · Viewed 23.8k times · Source

Hello looking for some help,

I currently have some JavaScript code that allows a signed in user to upload an image to Firebase storage. I want the image that they upload to be their profile picture, however I don't seem to be able to link the uploaded image back to the specific user?

It works, I can see the uploaded image in the console, but nothing to identify what user uploaded it.

//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;  
}}

I saw the code below in the Firebase documentation, but I don't understand how to update the photo URL image or display it.

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.
}

Many thanks in advance for any help or advice.

Answer

Mike McDonald picture Mike McDonald · Dec 20, 2016

You'll want to store the files by username:

// 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);

So if the user is user:12345 and the file name is profile.jpg, then the file will be saved as user:12345/profilePicture/profile.jpg. You can protect this with Security Rules as follows:

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/.+');
    }
  }
}