FileReader API:如何同步读取文件 [英] FileReader API: how to read files synchronously

查看:511
本文介绍了FileReader API:如何同步读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取在html页面上使用输入类型文件选择的文件。我已经实现了读取文件的功能,文件内容可以被读取。但实际的问题是读取文件的内容正在异步,这允许执行脚本的其他功能。我正在将读取的文件的内容存储在一个数组中。

在移动到其他函数时,数组是空的。当引入延迟时,数组有内容。任何人都可以帮我解决这个问题,而不会引入延迟?

我读取文件的代码是

  var getBinaryDataReader = new FileReader(); 
getBinaryDataReader.onload =(function(theFile){
return function(frEvnt)
{
file [fileCnt] = frEvnt.target.result;
}
})(document.forms [formPos] .elements [j] .files [0]);

getBinaryDataReader.readAsBinaryString(document.forms [formPos] .elements [j] .files [0]);

提前致谢。

方法

我认为你必须做一些异步调用(比如Ajax):将稍后需要运行的代码移动到读取文件时执行的回调函数中。

  getBinaryDataReader.onload = function(theFile){
// theFile.target.result有二进制
//你可以把它移动到数组
//(我想你已经正确地做了这个)
//然后...
nowCallTheOtherCodeThatNeedsToRunLater();

//或者如果你想等到数组中的所有元素
//被下载到
if(myArrayIsFullNow()){
callTheCodeThatNeedsTheFullArray();
}
// else:什么都不做,最后一个文件要完成下载
//会触发代码

}


I am trying to read a file which is selected using an input type file on the html page. I have implemented the function to read the file and the file content is able to be read. But the actual problem is that the reading of the content of the file is being done asynchronously which allows the other functions of the script to execute. I am storing the content of the file read in an array.

While moving to the other functions the array is empty. When delay is introduced then the array has the content. Can anybody help me out in solving this problem without introducing a delay?

My code for reading the file is

var getBinaryDataReader = new FileReader();
getBinaryDataReader.onload = (function(theFile) {
return function(frEvnt)
{
  file[fileCnt]=frEvnt.target.result;
}
})(document.forms[formPos].elements[j].files[0]);

getBinaryDataReader.readAsBinaryString(document.forms[formPos].elements[j].files[0]);

Thanks in advance.

解决方案

I think you have to do what you always have to with asynchronous call (like Ajax, too): Move the code that needs to run later into the callback that gets executed when the file has been read.

getBinaryDataReader.onload = function(theFile) {
   // theFile.target.result has your binary
   // you can move it into the array
   // (I think you are already doing this properly)
   // but then ...
   nowCallTheOtherCodeThatNeedsToRunLater();

   // or if you want to wait until all elements
   // in the array are downloaded now
   if (myArrayIsFullNow()){
      callTheCodeThatNeedsTheFullArray();
   }
   // else: do nothing, the final file to finish downloading
   // will trigger the code

} 

这篇关于FileReader API:如何同步读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆