As others said, I noticed that the onload event is missing.
So, I have several different ways to show how to get the reader to do something, one to execute readAsText and one to receive data as a base64 byte string using readAsDataURL , which is better in mine since you donβt have to worry about Unicode and other strange question mark characters. To see them in action, simply flip the call in the listener between uploadFile(); and uploadFile1(); . And I show a few different ways to capture a file object:
document.getElementById("myBtn").addEventListener("click", function() { uploadFile1(); }); function uploadFile1(){ var f = myInput.files[0]; var reader = new FileReader(); reader.onload = processFile(f); reader.readAsText(f); } function uploadFile(){ var f = document.querySelector('input').files[0]; var reader = new FileReader(); reader.onload = processFile(f); reader.readAsDataURL(f); } function processFile(theFile){ return function(e) {
<input id="myInput" type="file"> <button id="myBtn">Try it</button> <span id="file"></span>
And usually I would think you should just do:
<input type="button" onclick="uploadFile()" id="myBtn">Try it</button>
instead of adding this listener, but for some reason it did not work in JSFiddle.
https://jsfiddle.net/navyjax2/heLmxegn/1/
source share