JQuery loop on multiple input.files

I need to loop this on the input of several files:

var reader = new FileReader(); reader.onload = function (e) { $('#pprev_0') .attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); 

I tried this, but it does not work:

 var fileCount = 0; $("input[name='files[]']").each(function() { var reader = new FileReader(); reader.onload = function (e) { $('#pprev_'+fileCount) .attr('src', e.target.result) .css("display","block"); }; reader.readAsDataURL(input.files[fileCount]); fileCount++; }); 

alert () on output fileCount once 0 for multiple file selection. no additional warnings. If I take numbers instead of the fileCount var code in the code, it works in position. R.G. input.files [2] ...

Any idea?

+6
source share
1 answer

When you do this: $("input[name='files[]']").each(function() { you actually get any elements matching the selector. In this case, you get your only input for multiple files (so you you see only 1 warning, what you want to do is iterate over files.

There is code on this page that can be done exactly the way you want. I recommend you check:

http://www.html5rocks.com/en/tutorials/file/dndfiles/

To apply it to your situation, you would do something like this:

 var files = $('#files')[0].files; //where files would be the id of your multi file input //or use document.getElementById('files').files; for (var i = 0, f; f = files[i]; i++) { var reader = new FileReader(); reader.onload = function (e) { $('#pprev_'+fileCount) .attr('src', e.target.result) .css("display","block"); }; reader.readAsDataURL(f); } 
+7
source

All Articles