当用户使用HTML5 File API按下按钮时,如何读取本地文件? [英] How can I read a local file when the user presses a button using the HTML5 File API ?
问题描述
我正在尝试使用jQuery和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]);
当用户按下页面上的按钮时,将触发此代码。我的问题是,当代码运行时,文件
是未定义的,因此我无法从中获取所需的数据。如何获取输入文件的内容以便我可以将其作为参数传递给 FileReader.readAsText()
函数?
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?
推荐答案
files
数组是< input type = file>的属性。
DOMElement。我不知道如何使用jQuery访问它,但你总是可以使用 .get(0)
从jQuery元素获取支持DOMElement,这样你就可以访问你的文件了这里:
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;
或使用普通javascript:
Or with plain javascript:
var files = document.getElementById('file').files;
这篇关于当用户使用HTML5 File API按下按钮时,如何读取本地文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!