5

I am trying to upload a file using the HTML File Api but I really seem not to get how to do it. What event do I have to give to the getImg() function?

HTML

<input id='img' type='file' onchange='getImg(event)'/> 

JS

function getImg(evt){ var files = evt.dataTransfer.files; var file = files[0]; console.log(file.name) 

1 Answer 1

9

The dataTransfer object is for drag&drop operations. Use the target instead.

<!DOCTYPE html> <html> <body> <input id='img' type='file' onchange='getImg(event)'/> <script> function getImg(evt){ var files = evt.target.files; var file = files[0]; console.log(file.name); } </script> </body> </html> 
Sign up to request clarification or add additional context in comments.

2 Comments

Neat answer, but there is one problem with this solution. If you already uploaded a file, then changed the uploaded file to another file with the same name, then on change event is not triggered. That is an issue if you want more than the name changes such as reading the uploaded image as base64 string.
To fix it, I would set the value of the input with ID=img to be "" at the end fo getImg(evt), like $('#img').val(''); using Jquery for DOM selection.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.