简体   繁体   English

当用户使用HTML5 File API按下按钮时,如何读取本地文件?

[英]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. 我正在尝试使用jQuery和HTML5 File API从本地文件中获取数据。 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. 我的问题是,在代码运行时, files是未定义的,因此无法从中获取所需的数据。 How can I get the contents of the input file so that I can pass that as a parameter to the FileReader.readAsText() function? 如何获取输入文件的内容,以便可以将其作为参数传递给FileReader.readAsText()函数?

The files array is a property of a <input type=file> DOMElement. files数组是<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: 我不知道如何使用jQuery访问它,但是您始终可以使用.get(0)从jQuery元素获取支持的DOMElement,因此您可以在此处访问文件:

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

Or with plain javascript: 或使用普通的javascript:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM