简体   繁体   中英

multi upload images in same sequence as user input

I have a multi-upload for image files, and the problem that I used to face was that the images are appearing in a different sequence as the user's input. For example, user selects Img1, Img2, Img3, Img4. The sequence that it appears might be Img2, Img4, Img3, Img1.

This causes a problem as I have to link them to a text field (image description), and each text field has to match the right image. I did some digging and found out that i can use this code here to make sure that it is being uploaded in the same sequence:

html

<input id="uploadfiles" multiple="multiple" name="photos" type="file">

javascript

$("#uploadfiles").change(function(){
    imgpreview(document.getElementById('uploadfiles').files);
});

function imgpreview(files) {
    var count = 0;
    for (var i = 0, f; f = files[i]; i++) {
        (function () {
            var div = $("<div></div>");
            var reader = new FileReader();
            $(".display").append(div);    

            reader.onload = function(e) { 
                div.append("<img id='photocount" + count + "' src='" + e.target.result + "' style='height:40px;width:auto;'></img>");
                count++;
            };

            reader.readAsDataURL(f);
        }());
    } 
}

It is also available in fiddle here: https://jsfiddle.net/L3d1L9t3/1/

This javascript code here ensures that the images are appearing in sequence. However, the id for the images are still not in order. For example, if 4 images are uploaded, the ids should be photocount0, photocount1, photocount2, photocount3 respectively. But this is not the case when i inspect element on each of the images.

How do i ensure that the "count" is in sequence as well? This is important since i need to match the count to the text field (image description) as well ["image 1" is paired with "image description 1", "image 2" is paired with "image description 2" and so on]

Use URL.createObjectURL(file) instead it's both faster and easier since it's sync - you don't have to encode/decode back and fort to/from base64 then

$("#uploadfiles").change(function() {
  // imgpreview(document.getElementById('uploadfiles').files); <-- not needed
  imgpreview(this.files)
})

function imgpreview(files) {
  var url, div, len = files.length
  var $display = $(".display")

  for (var i = 0; i < len; i++) {
    url = URL.createObjectURL(files[i])
    div = $('<div>')
    $display.append(div)
    div.append("<img id='photocount" + i + "' src=" + url + " style='height:40px;width:auto'>")
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM