I’m rebuilding a multiple image upload function, but I came across the problem that fileReader()
is executed after the whole loop.
Inside the loop I’m 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 which gets cloned too.
For example I’m 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/
Advertisement
Answer
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++;
})
}