2012-01-13 138 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