How to upload images and display them using jquery?

Asked

Viewed 40 times

1

How do I upload images and display them within a div, and when the user uploads them again these images are 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() {
    var imagesPreview = function(input, placeToInsertImagePreview) {

    if (input.files) {
        var filesAmount = input.files.length;

        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]);
        }
    }

    };

    $('#gallery-photo-add').on('change', function() {
    imagesPreview(this, 'div.gallery');
    });
    });</script>
    <style>
    .gallery img{
    width: 90px;
    height: 55px;
    }
    </style>
    </head>
    <body>
    <input type="file" multiple id="gallery-photo-add">
    <div class="gallery"></div>
    </body>
    </html>

1 answer

2


Try to do it this way:

  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]);
        }
    }

};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.