K1-Aria
K1-Aria

Reputation: 1156

javascript FileReader multiple not working

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

Upvotes: 1

Views: 296

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138557

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

Upvotes: 1

Related Questions