27

我正在使用FileReader API 来读取多个文件。

<html> <body>
    <input type="file" id="filesx" name="filesx[]"
      onchange="readmultifiles(this.files)" multiple=""/>
    <div id="bag"><ul/></div>
<script>
window.onload = function() {
    if (typeof window.FileReader !== 'function') {
        alert("The file API isn't supported on this browser yet.");
    }
}

function readmultifiles(files) {
    var ul = document.querySelector("#bag>ul");
    while (ul.hasChildNodes()) {
        ul.removeChild(ul.firstChild);
    }

    function setup_reader(file) {
        var name = file.name;
        var reader = new FileReader();
        reader.onload = function(e) {
            var bin = e.target.result; //get file content

            // do sth with text

            var li = document.createElement("li");
            li.innerHTML = name;
            ul.appendChild(li);
        }
        reader.readAsBinaryString(file);
    }

    for (var i = 0; i < files.length; i++) { setup_reader(files[i]); }
}
</script> </body> </html>

问题是同时读取所有文件,当文件的总大小(总和)非常大时,浏览器会崩溃。

我想一个接一个地读取文件,这样可以减少内存消耗。

这可能吗?

4

9 回答 9

26

我自己想出了一个可行的解决方案。

function readmultifiles(files) {
  var reader = new FileReader();  
  function readFile(index) {
    if( index >= files.length ) return;
    var file = files[index];
    reader.onload = function(e) {  
      // get file content  
      var bin = e.target.result;
      // do sth with bin
      readFile(index+1)
    }
    reader.readAsBinaryString(file);
  }
  readFile(0);
}
于 2012-12-20T15:18:47.337 回答
17

这应该一个一个地读取文件:

function readmultifiles(files) {
    var ul = document.querySelector("#bag>ul");
    while (ul.hasChildNodes()) {
        ul.removeChild(ul.firstChild);
    }
    // Read first file
    setup_reader(files, 0);
}

// Don't define functions in functions in functions, when possible.

function setup_reader(files, i) {
    var file = files[i];
    var name = file.name;
    var reader = new FileReader();
    reader.onload = function(e){
                        readerLoaded(e, files, i, name);
                    };
    reader.readAsBinaryString(file);
    // After reading, read the next file.
}

function readerLoaded(e, files, i, name) {
    // get file content  
    var bin = e.target.result;
    // do sth with text

    var li = document.createElement("li");
    li.innerHTML = name;
    ul.appendChild(li);

    // If there's a file left to load
    if (i < files.length - 1) {
        // Load the next file
        setup_reader(files, i+1);
    }
}
于 2012-12-20T15:13:18.003 回答
14

为了新用户的利益,我正在更新这个问题,他们正在寻找通过FileReader API上传多个文件的解决方案,尤其是使用 ES。

与其手动迭代每个文件,不如Object.keys(files)在 ES中使用更简单、更简洁:

<input type="file" onChange="readmultifiles" multiple/>
<script>
function readmultifiles(e) {
  const files = e.currentTarget.files;
  Object.keys(files).forEach(i => {
    const file = files[i];
    const reader = new FileReader();
    reader.onload = (e) => {
      //server call for uploading or reading the files one-by-one
      //by using 'reader.result' or 'file'
    }
    reader.readAsBinaryString(file);
  })
};
</script>
于 2017-08-17T07:13:56.587 回答
3

我的完整解决方案在这里:

 <html> <body>
    <input type="file" id="filesx" name="filesx[]"
      onchange="readmultifiles(this.files)" multiple=""/>
    <div id="bag"></div>
<script>
window.onload = function() {
    if (typeof window.FileReader !== 'function') {
        alert("The file API isn't supported on this browser yet.");
    }
}

function readmultifiles(files) {
  var reader = new FileReader();  
  function readFile(index) {
    if( index >= files.length ) return;
    var file = files[index];
    reader.onload = function(e) {  
      // get file content  
      var bin = e.target.result;
      // do sth with bin
      readFile(index+1)
    }
    reader.readAsBinaryString(file);
  }
  readFile(0);

 function setup_reader(file) {
        var name = file.name;
        var reader = new FileReader();

            var ul = document.createElement("ul");
            document.getElementById('bag').appendChild(ul);
        reader.onload = function(e) {
            var bin = e.target.result; //get file content

            // do sth with text

            var li = document.createElement("li");
            li.innerHTML = name;
            ul.appendChild(li);
        }
        reader.readAsBinaryString(file);
    }

    for (var i = 0; i < files.length; i++) { setup_reader(files[i]); }
}
</script> </body> </html>
于 2019-08-13T13:10:52.540 回答
3

multiple使用属性定义输入:

<input onchange = 'upload(event)' type = 'file' multiple/>

定义上传函数:

const upload = async (event) => {
  
    // Convert the FileList into an array and iterate
    let files = Array.from(event.target.files).map(file => {

        // Define a new file reader
        let reader = new FileReader();

        // Create a new promise
        return new Promise(resolve => {

            // Resolve the promise after reading file
            reader.onload = () => resolve(reader.result);

            // Read the file as a text
            reader.readAsText(file);

        });

    });

    // At this point you'll have an array of results
    let res = await Promise.all(files);
  
}
于 2021-04-28T08:18:53.393 回答
2

我使用现代 JS(Map、Iterator)实现了另一个解决方案。我改编了我的 Angular 应用程序中的代码(最初是用一些 TS 功能编写的)。

就像 Steve KACOU 提到的,我们为每个文件创建一个不同的 FileReader 实例。

<input type="file" id="filesx" name="filesx[]"
      onchange="processFileChange(this)" multiple=""/>
    function processFileChange(event) {
        if (event.target.files && event.target.files.length) {
            const fileMap = new Map();

            for (let i = 0; i < event.target.files.length; i++) {
                const file = event.target.files[i];
                const fileReader = new FileReader();
                fileMap.set(fileReader, file);
            }

            const mapEntries = fileMap.entries();
            readFile(mapEntries);
        }
    }

    function readFile(mapEntries) {
        const nextValue = mapEntries.next();

        if (nextValue.done === true) {
            return;
        }

        const [fileReader, file] = nextValue.value;

        fileReader.readAsDataURL(file);
        fileReader.onload = () => {
            // Do black magic for each file here (using fileReader.result)

            // Read the next file
            readFile(mapEntries);
        };
    }

基本上,这利用了通过引用传递对象的优势,以使每次迭代都使地图永久化。在我看来,这使得代码很容易阅读。

于 2020-10-20T14:47:22.637 回答
1

您必须为要读取的每个文件实例化一个 FileReader 。

function readFiles(event) {
  //Get the files
  var files = event.input.files || [];
  if (files.length) {
    for (let index = 0; index < files.length; index++) {
      //instantiate a FileReader for the current file to read
      var reader = new FileReader();
      reader.onload = function() {
        var result = reader.result;
        console.log(result); //File data
      };
      reader.readAsDataURL(files[index]);
    }
  }
}

于 2020-01-19T00:06:53.547 回答
0

采取这些答案的最佳部分。

<input type="file" onchange="readmultifiles(this.files)" multiple />
<script>
function readmultifiles(files) {
  for (file of files) {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.fileName = file.name;
    reader.onload = (event) => {
      const fileName = event.target.fileName;
      const content = event.currentTarget.result;
      console.log({ fileName, content });
    };
  }
}

</script>
于 2020-06-28T17:28:14.973 回答
0

试试这个

const setFileMultiple = (e) => {
  e.preventDefault();
  //Get the files
  let file = [...e.target.files] || [];

  file.forEach((item, index) => {
    let reader = new FileReader();

    reader.onloadend = () => {
      console.log("result", reader.result);
    };
    reader.readAsDataURL(file[index]);
  });

};
于 2021-10-25T20:11:03.820 回答