使用 Javascript 读取多个文件会导致只读取最后一个文件

Reading in multiple files with Javascript results in only last file being read

我必须将一些测试文本文件读入我的 JavaScript 代码中。有 3 个文件,标题为 1.txt2.txt3.txt,每个文件包含一行。我写了这段我认为可以正常工作的代码:

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        console.log("Start loop")
        myFile = files.item(i);
        var myReader = new FileReader();
        myReader.readAsText(myFile);
        myReader.onload = function(e) {
            var rawLog = myReader.result;
            console.log(rawLog)
        };

    }
};

document.getElementById('files').addEventListener('change', handleFileSelect, false);

这会在网页上生成一个按钮,允许我 select 多个文件。它应该导致以下结果:

Start loop
Contents 1.txt
Start loop
Contents 2.txt
Start loop
Contents 3.txt

但是它输出的是以下内容:

Start loop 
Start loop
Start loop
null
null
Contents 3.txt

如何生成第一个?我希望错误出现在 onload 函数中,但我不确定我做错了什么...

在您的代码中,var myReader = new FileReader(); 在每个循环中重新分配变量,从而破坏第一个实例。

我建议您将代码拆分为两个函数,以防止局部块变量的实例在完成之前被覆盖。

function readFile(file) {
    var myReader = new FileReader();
  myReader.readAsText(file);
  myReader.onload = function(e) {
      var rawLog = myReader.result;
      console.log(rawLog)
  };
} 

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        myFile = files.item(i);
        readFile(myFile);
    }
};