Francisco Romero
Francisco Romero

Reputation: 13199

How to choose a file with Javascript?

I am trying to create a Browser Dialog to let the user upload images to my webpage.

I know that I have to use an <input type="file"> but I do not know where (or better, when) retrieve the information when the user has accepted the prompt that appears when you click on the button.

In my case, when you click on a button, the prompt appears and I handle this event via Javascript.

Here is my code:

window.onload = function(){ 
  var buttonFile = document.getElementById("buttonFile");
  var file = document.getElementById("file");

  buttonFile.onclick = function(){
    document.getElementById("file").click();
  }

  var files = document.getElementById('file').files[0]; //I do not know where to put this line
  alert(files);
};			
#file{
  display: none;
}
<input type="file" id="file" accept=".jpg, .png, .jpeg">
<button id="buttonFile">Upload file</button>

Of course, now is retrieving undefined because I am trying to retrieve it regardless if the prompt has appeared or not. If I put the line inside the onclick event of the button it also does not have the info yet. I also tried to create an onclick event for the file, but it also does not retrieve the info because it does not know when it has been accepted.

So here I have some questions:

Thanks in advance!

Upvotes: 5

Views: 6377

Answers (2)

A.J.
A.J.

Reputation: 393

You've got everything right so far, except you don't need to get the value of the files until the user has uploaded them. Otherwise, it will definitely be undefined.

window.onload = function() { 
  var buttonFile = document.getElementById("buttonFile");
  var file = document.getElementById("file");

  buttonFile.onclick = function() {
    document.getElementById("file").click();
  };

  file.onchange = function(e){
     if (this.files && this.files[0]) {
        alert(JSON.stringify(this.files[0]));
     }
  };
};

1) You shouldn't put the line in the onclick handler at all. 2) You're correct in that older browsers don't check for the type. Regardless you should ALWAYS do server side validation. 3) Unless you decide to use web services.

Upvotes: 3

Jon Koops
Jon Koops

Reputation: 9261

window.onload = function() { 
  var buttonFile = document.getElementById("buttonFile");
  var file = document.getElementById("file");

  buttonFile.onclick = function() {
    document.getElementById("file").click();
  };

  file.onchange = function() {
    alert(file.files[0].name);
  };
};
#file{
  display: none;
}
<input type="file" id="file" accept=".jpg, .png, .jpeg">
<button id="buttonFile">Upload file</button>

Upvotes: 0

Related Questions