简体   繁体   中英

How to give an image a different id each time it gets uploaded

I'm currently testing out a piece of code by user OGiS0. It is a javascript code that uploads images. How would I make it so that every time an image gets uploaded, it gets a new ID so I can drag and drop it without interference.

window.onload = function(){

//Check File API support
if(window.File && window.FileList && window.FileReader)
{
    var filesInput = document.getElementById("files");

    filesInput.addEventListener("change", function(event){

        var files = event.target.files; //FileList object
        var output = document.getElementById("result");

        for(var i = 0; i< files.length; i++)
        {
            var file = files[i];

            //Only pics
            if(!file.type.match('image'))
              continue;

            var picReader = new FileReader();

            picReader.addEventListener("load",function(event){

                var picFile = event.target;

                var div = document.createElement("div");

                div.innerHTML = "<img id='thumbnail' draggable='true' ondragstart='drag(event)' src='" + picFile.result + "'" +
                        "title='" + picFile.name + "'/>";


                output.insertBefore(div,null);            

            });

             //Read the image
            picReader.readAsDataURL(file);
        }                               

    });
}
else
{
    console.log("Your browser does not support File API");
}

}

Fiddle to show how it works: http://jsfiddle.net/Yvgc2/1563/

Currently, all the images have the same id when uploaded so drag and drop cannot occur.

Quick and dirty: use a global variable ( window.thumbId ).

The reason why you shouldn't use the i variable is, that it will restart each time you upload picture(s).

window.thumbId will work regardless how many times and how many images you upload. You'll get ids like thumbnail1 , thumbnail2 , etc:

window.thumbId = (window.thumbId || 0)+1;
div.innerHTML = "<img id='thumbnail"+window.thumbId+"' draggable='true' ondragstart='drag(event)' src='" + picFile.result + "'" +
                            "title='" + picFile.name + "'/>";

If the files get stored in a DB, you can use the db index as a unique id, get last index and +1 on each new item.

If not you can use the loops index and replace this line

div.innerHTML = "<img id='"+i+"' draggable='true' ondragstart='drag(event)' src='" + picFile.result + "'" +
                        "title='" + picFile.name + "'/>";

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