I am writing a program that shows previews of images by adding them to table cells. In the neighboring cells there are fields for the name, tags and source of the uploaded photos, which I also fill out, and then I upload all this information along with the files to the server. I use the FileReader object, which in turn writes files using the readAsDataUrl method. But the problem is that this method works asynchronously and as a result I see the preview not in the order in which the files will be uploaded to the server, and the previews themselves do not correspond to the files that stand behind them, it turns out a shuffle. This caused a problem, because the file descriptions that the user enters (name, tag, source) as a result do not match the picture.
Here's what it looks like (note the descriptions). Loading process:
Download result:
Here, people have already raised and solved a similar problem, but I do not know how to apply these ideas in my case, when for each preview the elements of the table are dynamically created. Please help.
My code is:
Javascript
$(document).ready(function () { $("#fileUpload").on('change', function () { //Get count of selected files var countFiles = $(this)[0].files.length; var imgPath = $(this)[0].value; var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase(); var image_holder = $("#image-holder"); image_holder.empty(); if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") { if (typeof(FileReader) != "undefined") { //loop for each file selected for uploaded. var newElem = document.createElement('table'); newElem.id = 'tl'; newElem.align = 'center'; newElem.border = 0; for (var i = 0; i < countFiles; i++) { var reader = new FileReader(); reader.onload = function (e) { var newRow = newElem.insertRow(0); var newCell1 = newRow.insertCell(0); newCell1.innerHTML = "<input type='text' class='form-control' " + "placeholder='Source' name='source' style='margin: 15px'>"; var newCell2 = newRow.insertCell(0); newCell2.innerHTML = "<input type='text' class='form-control' " + "placeholder='Tags' name='tags' style='margin: 10px'>"; var newCell3 = newRow.insertCell(0); newCell3.innerHTML = "<input type='text' class='form-control' " + "placeholder='Name' name='name' style='margin-left: 5px'>"; var newCell4 = newRow.insertCell(0); $("<img />", { "src": e.target.result, "class": "thumb-image" }).appendTo(newCell4); }; document.getElementById("image-holder").appendChild(newElem); reader.readAsDataURL($(this)[0].files[i]); image_holder.show(); } } else { alert("This browser does not support FileReader."); } } else { alert("Please select images only"); } }); }); HTML:
<form method="POST" action="upload" enctype="multipart/form-data"> <input id="fileUpload" name="file" multiple="multiple" type="file"/> <br/> <input type="submit" value="Upload" class="btn btn-primary btn-lg"> <br/> <div id="image-holder"/> </form> 
