Search code examples
jqueryloopsparsingfilereaderhtml5-filesystem

Filereader gets overwritten when multiple files are active


I'm trying to parse 2 or more xml files at once. Means I can choose for example 5 .xml files, then it should get parsed via jQuery plugin and written on the page afterwards. Now my problem: The second, third etc. iteration of the loop fires too early so the first file gets "lost".

My attempt:

var input = $("#xmlInput");
input.change(function () {
   var inputfiles = input[0].files;
   for (var i = 0; i < inputfiles.length; i++) {
      var reader = new FileReader();
      reader.readAsText(inputfiles[i]);
      reader.onloadend = function () {
         var data = $.xml2json(reader.result);
         console.log(data);
         //write(data);
      }
    }
 });   

Solution

  • Found the answer on an other so question:

    (function (file) {
       var reader = new FileReader();
       reader.onload = function (readerData) {
          var data = $.xml2json(readerData.target.result);
          write(data);
       }
       reader.readAsText(file);
    })(inputfiles[i]);
    

    Works like a charm. =)