admin管理员组

文章数量:1317905

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 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.

Share Improve this question edited May 30, 2013 at 18:10 Sz. 3,6441 gold badge32 silver badges45 bronze badges asked Jan 13, 2012 at 12:15 AmGatesAmGates 2,12316 silver badges29 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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

} 

本文标签: javascriptFileReader API how to read files synchronouslyStack Overflow