KarthickN
KarthickN

Reputation: 335

Getting the content of each file in multiple file input using jquery

I need to fetch the content of each file in multiple file input using jquery and based on the file content i need to do some modifications in my page. Here is the code I have written to do the same. Here what is happening is If I select 3 files I am getting the content of 3rd file alone. If I use the index number instead of looping I am able to get the contents But If I use looping I am getting the last files content alone. Could someone explain me whats wrong with it ?

<input type="file" name="xsd" id="xsd" multiple="multiple">

     $('#xsd').change(function(){  

        input = document.getElementById('xsd');
        for(var i = 0; i < input.files.length ; i++)
        {
        file = input.files[i];
        fr = new FileReader();
        fr.readAsText(file);
        fr.onload = function(e) {
            var filecontent = fr.result;
            // My logic here
        } 
       }
    });

Upvotes: 0

Views: 1779

Answers (1)

folkol
folkol

Reputation: 4883

Your problem is that the onload function is getting it's "fr" from a closure.

You can create a separate closure for each of the onload-callbacks by using an immediately-invoked anonymous function like this:

$('#file').change(function(){  

    input = document.getElementById('file');
    for(var i = 0; i < input.files.length ; i++)
    {
        (function(i) {
            var file = input.files[i];
            var fr = new FileReader();
            fr.onload = function(e) {
                var filecontent = fr.result;
                // My logic here
            }
            fr.readAsText(file);
        })(i);
   }
});

Upvotes: 2

Related Questions