0

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
        } 
       }
    });

1 Answer 1

2

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

6 Comments

<input type="file" name="xsd" id="xsd" multiple="multiple"> I have only one file input which accepts multiple files.
Yes, I mis-read your question. I updated the answer after that.
Basically: You iterate three times in the loop before the first onload function is invoked, and once that is invoked, it will find and use the last "fr" value, which is from the last iteration of the loop.
I just saw a typo in my answer (I forgot the curly brackets in the anonymous function). I should start running my examples before I post them :P
Still I am not able to get the contents of all the files. Only the last file's content are getting fetched
|

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.