FileReader API:如何同步读取文件

发布于 2024-12-26 12:47:44 字数 545 浏览 2 评论 0原文

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

提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三五鸿雁 2025-01-02 12:47:44

我认为您必须执行异步调用(也如 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

} 

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

} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文