1

I'm using one input in html to select and upload image one by one or multiple.

I want to show preview before upload image and I'm using js FileReader. It's working for one image but not working for multiple images.

$('#fileToUpload').change(function(){
    var file = this.files;
    filepreview(file);
});



function filepreview(files)
{
    var length = files.length;

    for(var i=0 ; i<length ; i++)
    {
            var file = files[i];

            var reader = new FileReader();
            reader.addEventListener("load",function(e){
                $('#pic'+i+'').attr('src' , ''+e.target.result+'');
            });
            reader.readAsDataURL(file);
    }
}
Talha Awan
  • 4,573
  • 4
  • 25
  • 40
K1-Aria
  • 1,093
  • 4
  • 21
  • 34
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Jonas Wilms Jul 10 '17 at 17:02

1 Answers1

1

Its basically that i is always length, as the events occur after the loop iterated:

reader.addEventListener("load",function(e){//async stuff
            $('#pic'+i+'').attr('src' , ''+e.target.result+'');//i = length
});

So you may want to bind i:

reader.addEventListener("load",function(i,e){//take over the bound i
            $('#pic'+i+'').attr('src' , ''+e.target.result+'');
}.bind(this,i));//the magic part
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151