Javascript Javascript文件阅读器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11725272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript File Reader
提问by Steven Stangle
I may just not be understanding the file reader api, but
我可能只是不理解文件阅读器 api,但是
When I try to run:
当我尝试运行时:
for (var i = 0, f1, f2; f1 = files[sorted_index[i]], f2 = files[sorted_index[i+1]]; i=i+2) {
var file_one;
var file_two;
if(f1.size < f2.size){
file_one = f1;
file_two = f2;
} else {
file_one = f2;
file_two = f1;
}
var file_one_contents;
var file_two_contents;
var reader = new FileReader();
reader.readAsText(file_one);
reader.onload = readSuccess;
function readSuccess(evt){
file_one_contents = evt.target.result;
}
var reader = new FileReader();
reader.readAsText(file_two);
reader.onload = readSuccess2;
function readSuccess2(evt2){
file_two_contents = evt2.target.result;
}
console.log(file_one_contents);
console.log(file_two_contents);
The console log only contains undefinedin it. The goal of the script it two read in two CSVs and take the data from the pair of files and do some computations.
控制台日志中只包含undefined。脚本的目标是读取两个 CSV 文件并从这对文件中获取数据并进行一些计算。
Thanks!
谢谢!
回答by Pointy
The API is asynchronous. The "success" functions are called when the operation completes, and that won't be immediate.
API 是异步的。“成功”函数在操作完成时被调用,这不会立即生效。
Move your console.log()
calls to insidethe handler functions.
将您的console.log()
调用移动到处理程序函数内部。
edit— If you need to wait to start doing stuff until both files are ready, you can do something like this:
编辑- 如果您需要等到两个文件都准备好后再开始做某事,您可以执行以下操作:
var countdown = 2;
var reader = new FileReader();
reader.readAsText(file_one);
reader.onload = readSuccess;
function readSuccess(evt){
file_one_contents = evt.target.result;
countdown--;
if (countdown === 0) go();
}
var reader = new FileReader();
reader.readAsText(file_two);
reader.onload = readSuccess2;
function readSuccess2(evt2){
file_two_contents = evt2.target.result;
countdown--;
if (countdown === 0) go();
}
There are more sophisticated ways to do it, of course, but that simple trick just waits until the counter is zero before calling "go()", which represents the function that'd work on processing the files.
当然,还有更复杂的方法可以做到这一点,但这个简单的技巧只是在调用“go()”之前等待计数器为零,它表示处理文件的函数。
回答by Lars GJ
I had a similar problem which solved the file read waiting by using ".onloadend" instead of "onload". In the code below x is bound to a "div" element
我有一个类似的问题,它通过使用“.onloadend”而不是“onload”解决了文件读取等待。在下面的代码中,x 绑定到一个“div”元素
reader.onloadend = function (evt) {
x.innerHTML = evt.target.result;
}
With "onload" it was all undefined.
使用“onload”,一切都是未定义的。