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

喜你入骨 提交于 2019-12-12 03:10:08

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/9979464/how-can-i-read-a-local-file-when-the-user-presses-a-button-using-the-html5-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!