Search code examples
javascriptjqueryuploadpreview

jQuery image preview for multiple image upload


I am using this code in my image uploader:

Html:

<input type="file" id="files" name="files[]" multiple />
<ul id="list"></ul>

JS:

function handleFileSelect(evt) {
var files = evt.target.files; // FileList object

for (var i = 0, f; f = files[i]; i++) {

  if (!f.type.match('image.*')) {
    continue;
  }

  var reader = new FileReader();

  reader.onload = (function(theFile) {
    return function(e) {
      var li = document.createElement('li');
      li.innerHTML = ['<img class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/><input type="text" class="rename" name="',i,'" value="',escape(theFile.name),'"><input type="text" class="reorder" name="',i,'" value="',i,'">'].join('');
      document.getElementById('list').insertBefore(li, null);
    };
  })(f);

  reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);

My problem is when it gets to reader.onload, the for loop is done so i = #of images not image # like I want it to be. Is there any way to fix this so the name of my inputs is the image # of the image they're next to?


Solution

  • reader.onload runs as many times as there are pictures being uploaded.

    var x = 0;
      reader.onload = (function(theFile) {
        return function(e) {
    
          console.log(x);
    
          x++;
    
        };
      })(f);