6

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.

1 Answer 1

11

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]);
     }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.