0

Im rebuilding a multiple image upload function.

But i came across with the problem that fileReader() is executed after the whole loop.

Inside the loop im cloning foreach dragged image a container expect first one. This container has the class and id "clonemulti". Inside this container is the "file-return" container wich get cloned too.

For example im dragging into the file input field 3 images. The loop runs through, the ParseFile() function is appending to each "file-return" step by step the values for name and size each image (1,2,3), but the setupReader() function appends all images just to the last (3) container.

var files = e.target.files || e.dataTransfer.files;
$('.clonemulti').slice(1).remove();
for (var i = 0, f; f = files[i]; i++) {     

            if(i > 0){
                $newimg = $('#clonemulti').clone();
                $newimg.removeAttr('id');
                $newimg.find('.file-return p').remove('p');
                $newimg.insertAfter( ".clonemulti:last" );  
            } 


            $('.filenameauto').last().val(f.name);
            ParseFile(f);   
            setupReader(f);
        }


function ParseFile(file) {


  String.prototype.trunc = String.prototype.trunc ||
  function(n){
      return (this.length > n) ? this.substr(0, n-1) + '…' : this;
  };

   var filenametrunc = file.name.trunc(25);

    fileinputappend = 
        "<p class='center'><span class='imagesrc'></span><br/> <strong>" + filenametrunc +
        "</strong> size: <strong>" + Math.round(file.size /1000)  +
        "</strong> Kb</p>";


    $( fileinputappend ).appendTo( '.file-return:last' );          

}

    function setupReader(file) {
            var reader = new FileReader();
            reader.onload = function(event) {
                $($.parseHTML('<img>')).attr('src', event.target.result).appendTo('.imagesrc:last');

            }
           reader.readAsDataURL(file);


    }

How can i handle the setupReader() function get executed and appending images to the last "file-return" "imagesrc" class like the ParseFile() function does ?

This is a Fiddle of an example: https://jsfiddle.net/3xtg6hew/1/

delato468
  • 424
  • 2
  • 15

1 Answers1

0

I solved the problem by myself, with making an own loop where i looping each class and adding the image there:

    function setupReader(file) {
        var z = 0;
        $('.imagesrc').each(function(){
            var reader = new FileReader();
            var thisclass = $(this);

            reader.onload = function(event) {

                var appendattr = $($.parseHTML('<img>')).attr('src', event.target.result);
                $(thisclass).append(appendattr);

            }
           reader.readAsDataURL(file[z]);

           z++;

        })

    }
delato468
  • 424
  • 2
  • 15