0

I am a newbie to firebase and Javascript.
How do I change the file name to user's uid and save it to storage? And I want to upload a file after successful registration. Should I write a function in createUserWithEmailAndPassword or 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);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Li Optt
  • 19
  • 2

2 Answers2

0

You can't change the file name directly. But there is an indirect way to do that, check this question

You want User's UID as file name but you won't get that in createUserWithEmailAndPassword so you need to add that logic into onAuthStateChanged method. But onAuthStateChanged get called every time whenever users login so you need to build some kind of logic to execute your file upload method only first time when user log in.

Shahnaz Khan
  • 1,055
  • 1
  • 14
  • 26
0

To take an action in response to the user account being created, you can use then.

So something like:

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) {
        ...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807