2012-01-13 478 views
4

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

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

我的文件进行读取的代码是提前

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]); 

感谢。

回答

5

我认为你必须做一些异步调用(如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 

} 
+0

你可以给我例举FileReader与回调 – AmGates 2012-01-13 12:20:23

相关问题