Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Where should I put this line to get the value of the image that I am uploading?
  • As the filter of the input is not supported for old browsers, should I check it on the server side also, right?
  • If I want to check it on the server side (PHP), have I to link it to a form?

Thanks in advance!

like image 504
Francisco Romero Avatar asked Oct 31 '22 03:10

Francisco Romero


1 Answers

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.

like image 65
A.J. Avatar answered Nov 14 '22 05:11

A.J.