How can I read a local file when a user clicks a button using the HTML5 API files?

I am trying to use jQuery and the HTML5 file APIs to get data from a local file. I want to read the file and get text from it, but only when the user clicks the button, and not when the contents of the input field change.

Here is the code I'm using now:

files = $("#file").files; var reader = new FileReader(); reader.onload = function(event) { var content = event.target.result; alert(content); agregar(content[0]); alert(content); } reader.readAsText(files[0]); 

This code runs when the user clicks a button on the page. My problem is that when I run the code, the files are undefined, and therefore I cannot get the data I need. How can I get the contents of the input file to pass this as a parameter to the FileReader.readAsText() function?

0
source share
1 answer

The files array is a property of <input type=file> DOMElement. I don't know how to access it using jQuery, but you can always get DOMElement support from the jQuery element with .get(0) so that you can access your files here:

 var files = $('#file').get(0).files; 

Or with simple javascript:

 var files = document.getElementById('file').files; 
+1
source

Source: https://habr.com/ru/post/1411661/


All Articles