Reading multiple files in a loop using HTML5 File API

HQXU85 picture HQXU85 · Jul 26, 2013 · Viewed 8.5k times · Source

I am using the HTML5 File API to read binary files. The user can select multiple files and then click a button to copy them into a JavaScript object. My code is listed here:

   <script>         
     var data = new Object;
     function ReadFiles()
     {
         var files = document.getElementById('file').files;
         for (var i = 0; i < files.length; i++) {
             var reader = new FileReader();
             reader.onloadend = function (evt) {
                 if (evt.target.readyState == FileReader.DONE) {
                     data["File_Content" + i] = btoa(evt.target.result);
                 }
             };
             reader.readAsBinaryString(files[i]);
         }
     }
   </script>
   <input type="file" id="file" name="file[]" multiple />
   <button onclick="ReadFiles();">Read Files</button>

If the user puts in three files, then only an invalid property 'File_Content3' will be added to the 'data' object with value; the other three valid properties 'File_Content0', 'File_Content1' and 'File_Content2' are not created.

Can anybody solve the problem? Thanks.

Answer

Musa picture Musa · Jul 26, 2013

You have a clouse issue with the i variable, I'd simply use another variable

     var j = 0, k = files.length;
     for (var i = 0; i < k; i++) {
         var reader = new FileReader();
         reader.onloadend = function (evt) {
             if (evt.target.readyState == FileReader.DONE) {
                 data["File_Content" + j] = btoa(evt.target.result);
                 j++;
                 if (j == k){
                     alert('All files read');
                 }
             }
         };
         reader.readAsBinaryString(files[i]);
     }