How to upload images and display them using jquery?

1

How do I upload images and display them within a div, and when the user re-uploads those images to be replaced. Ex: the user uploads images img1.jpg, img2.jpg if he uploads new images img3.jpg, img4.jpg the first image should disappear. In the code below the images are added but the first images still continue.

    <html>
    <head>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script><script>$(function(){varimagesPreview=function(input,placeToInsertImagePreview){if(input.files){varfilesAmount=input.files.length;for(i=0;i<filesAmount;i++){varreader=newFileReader();reader.onload=function(event){$($.parseHTML('<img>')).attr('src',event.target.result).appendTo(placeToInsertImagePreview);}reader.readAsDataURL(input.files[i]);}}};$('#gallery-photo-add').on('change',function(){imagesPreview(this,'div.gallery');});});</script><style>.galleryimg{width:90px;height:55px;}</style></head><body><inputtype="file" multiple id="gallery-photo-add">
    <div class="gallery"></div>
    </body>
    </html>
    
asked by anonymous 30.09.2017 / 20:37

1 answer

2

Try to do this:

  var imagesPreview = function(input, placeToInsertImagePreview) {
    if (input.files) {
        var filesAmount = input.files.length;
        $(placeToInsertImagePreview).empty(); // remove as imagens antigas
        for (i = 0; i < filesAmount; i++) {
            var reader = new FileReader();
            reader.onload = function(event) {
                $($.parseHTML('<img>')).attr('src',
                event.target.result).appendTo(placeToInsertImagePreview);
            }
            reader.readAsDataURL(input.files[i]);
        }
    }

};
    
30.09.2017 / 20:47