Reading multiple files in a loop using the HTML5 file API

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 places three files, then only the invalid property 'File_Content3' with value will be added to the 'data' object; the other three valid properties "File_Content0", "File_Content1" and "File_Content2" are not created.

Can anyone solve the problem? Thanks.

+6
source share
1 answer

You have a problem with variable i , I would just 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]); } 
+11
source

Source: https://habr.com/ru/post/950325/


All Articles