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!
document.getElementById('file').files[0]inside anonchangehandler on the<input>element.