Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript add remove multiple image upload

I am creating add remove image upload. When I add 1 image's file, it will automate create new input file property without button clicked (only click on input property).

When I click del icon to delete the image's file, the image's preview has been removed but input property belong the image still exist, and the result all image’s file post by submit include the delete’s image.

Could you help me to modify this javascript so when I delete the image, it also delete the input property belong it's image, please?

    var abc = 0;
    $(document).ready(function() {
    $('body').on('change', '#file', function(){
        if (this.files && this.files[0]) {
            abc += 1;   
            $(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");

            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);

    //      $(this).hide();
            $("#abcd"+ abc).append($("<img/>", {id: 'x', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().remove();
            }));
        }
        $(this).after($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
                    $("<input/>", {name: 'file[]', type: 'file', id: 'file'})
        ));
    });

    //To preview image     
        function imageIsLoaded(e) {
            $('#previewimg' + abc).attr('src', e.target.result);
        };
    });
    #file{
        color:green;
        padding:5px; border:1px dashed #123456;
        background-color: #f9ffe5;
    }

    #x{ 
        width: 17px;
        height: 17px;
        border: none; 
        margin-left: -20px;
        margin-top: 1px;
        cursor: pointer;
        position: absolute;
    }

    .abcd img{
        height:100px;
        width:100px;
        padding: 5px;
        border: 1px solid rgb(232, 222, 189);
    }
    <form enctype="multipart/form-data" action="" method="post">
        <div id="filediv">
            <input name="file[]" type="file" id="file"/>
        </div><br/> 
        <input type="submit" value="Upload File" name="submit"/>
    </form>

running on jsfiddle

like image 997
Erica Avatar asked Dec 20 '25 01:12

Erica


2 Answers

Its too much to rewrite but i can point you to two problems with your code:

  1. hierachy: you keep creating divs inside the previous file-upload divs. These "should" be siblings and not children. Attach things to the .parent() element

  2. ID:s should be unique. You file upload elements and the filedivs all have the same ID, try to add the abc incrementing variable you have to those newly created elements

like image 88
BobbyTables Avatar answered Dec 22 '25 15:12

BobbyTables


  • demo: https://so.lucafilosofi.com/javascript-add-remove-multiple-image-upload/

your code completely rewrited and fully working

   var files = [];
    $(document).on('change', '#file', function() {

        var index = $('.file-wrapper').length ? $('.file-wrapper:last-child').data('index') + 1 : 0;

        if (this.files) {

            console.log('files', this.files);

            $.each(this.files, function(i, file) {

                var reader = new FileReader();

                files[index] = file;

                var template = '<div id="file-wrapper-%d" data-index="%d" class="col-4 file-wrapper">' +
                    '<div class="card p-2">' +
                    '<div class="card-header p-2"><strong>' +
                    file.name +
                    '</strong></div><div class="card-body p-2 text-center">' +
                    '<img src="%s" class="img-fluid" alt="" style="max-height:150px" /></div>' +
                    '<div class="card-footer p-2">' +
                    '<a href="#" data-index="%d" class="float-left delete-image btn btn-sm btn-danger"><i class="fas fa-trash-alt"></i></a>' +
                    '<strong class="float-right">' +
                    formatSizeUnits(file.size) +
                    '</strong>' +
                    '</div>' +
                    '</div></div>';


                reader.onload = function(e) {

                    console.log('reader', reader, e);

                    // create the form data object
                    // and pass some additional parameters

                    var data = new FormData();
                    data.append('fileName', file.name);
                    data.append('fileIndex', index);
                    data.append('fileBlob', reader.result);
                    data.append('action', 'upload');

                    // upload to server
                    $.ajax({
                        type: 'POST',
                        url: 'api.php',
                        data: data,
                        processData: false,
                        contentType: false
                    }).done(function(json) {
                        console.log('ajax:upload', json);
                        $('#files-wrapper').append(template.replace(/(%d)/g, index).replace(/(%s)/g, reader.result));
                        $("#file-wrapper-" + index).fadeIn(200);
                        index++;
                    });
                }
                reader.readAsDataURL(file);
            });
        }
    });
  • see the demo source for css code...
like image 23
Luca Filosofi Avatar answered Dec 22 '25 13:12

Luca Filosofi