简体   繁体   中英

Delete image preview before upload

I am uploading multiple images and showing preview, it is working fine. When I want to delete a particular preview image the preview image is deleted but when I upload all the files are uploading. Please check.

My form:

<div class="form-group">
    <div class="row">
        <div class="col-sm-12 col-md-6 col-lg-5">
            Upload a file(.csv,.xls,.xlsx)
        </div> 
        <div class="col-sm-12 col-md-6 col-lg-7">
            <input type="file" class="form-control" id="gallery-photo-add" name="projectfile[]" multiple>
            <div class="gallery">
            </div>        
        </div> 
    </div>
</div>

Javascript

$(function() {
    var imageArray = [];
    var imagesPreview = function(input, placeToInsertImagePreview) {
        var data = '';
        if (input.files) {
            var filesAmount = input.files.length; 

            for (let i = 0; i < filesAmount; i++) {
                data +='<li>'+ input.files[i].name + '</li>';

                var reader = new FileReader();
                reader.onload = function(event) {
                    var image = '<a class="delete" data-value='+ i +'><img class="images" src='+ event.target.result +'><i class="fas fa-times closeicon" aria-hidden="true"></i> </a>';
                    $($.parseHTML(image))
                        .appendTo(placeToInsertImagePreview);
                }   
                // console.log(input.files);
                reader.readAsDataURL(input.files[i]);
                imageArray.push(input.files[i]);
                console.log(imageArray);    
            } 
        }
    };

    $('#gallery-photo-add').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });

    $("div.gallery").on('click','.delete',function(){
        // console.log($(this).data("value"));
        $(this).remove();
        imageArray.splice($(this).data("value"),1);
        console.log(imageArray);
     });
});

Multiple input type file return a read-only fileList . It contains a collection of File objects. Therefore u can't simply remove an element from this list.

You have to use AJAX to handling the Form. Refer this question.

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