【问题标题】:FileReader API: how to read files synchronouslyFileReader API:如何同步读取文件
【发布时间】:2012-01-13 12:15:17
【问题描述】:

我正在尝试读取使用 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]);

提前致谢。

【问题讨论】:

    标签: javascript file-io asynchronous synchronized


    【解决方案1】:

    我认为您必须对异步调用(也像 Ajax)做您一直需要做的事情:将需要稍后运行的代码移到读取文件时执行的回调中。

    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 的例子吗
    猜你喜欢
    • 2023-03-10
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2019-07-04
    • 1970-01-01
    • 2012-09-04
    相关资源
    最近更新 更多