Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple files with Javascript FileReader API one at a time

I'm using the FileReader API to read multiple files.

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

The problem is that all files are read at the same time, and when the files have a total size (sum) that is very large, the browser crashes.

I want to read one file after another, so that the memory consumption is reduced.

Is this possible?

like image 476
xaedes Avatar asked Dec 20 '12 15:12

xaedes


People also ask

How does FileReader work JavaScript?

Introduction to the JavaScript FileReader API And JavaScript uses the FileList object to hold the File objects. To read the content of a file, you use the FileReader object. Note that the FileReader only can access the files you selected via drag & drop or file input.


1 Answers

I came up with a solution myself which works.

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); } 
like image 99
xaedes Avatar answered Oct 08 '22 23:10

xaedes