Search code examples
javascriptjqueryhtmlfileapi

How can I read a local file when the user presses a button using the HTML5 File API ?


I'm trying to use jQuery and the HTML5 File API to get data from a local file. I want to read the file and get text from it, but only when the user presses a button, not when the input field's content changes.

Here's the code I'm currently using:

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 is triggered when the user presses a button on the page. My problem is that when the code runs, files is undefined and so I can't get the data I need from it. How can I get the contents of the input file so that I can pass that as a parameter to the FileReader.readAsText() function?


Solution

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

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

    Or with plain javascript:

    var files = document.getElementById('file').files;