Erica
Erica

Reputation: 31

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

Upvotes: 3

Views: 3338

Answers (4)

Watch-Online.in
Watch-Online.in

Reputation: 25

<input type="file" id="fileInput" name="image[]" multiple class="opacity-0" />
<div id="thumb-output" class="grid grid-cols-3 gap-2"></div>

<div class="bg-black text-white rounded p-2 cursor-pointer mt-5" id="showFiles">Show Files</div>


<script type="text/javascript">
//Preview
$("#fileInput").on("change", function(e) {
    var files = e.target.files;
    var filesLength = files.length;
    for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
            var file = e.target;
            var img = '<div class="img-wrap"><span id="deleteImage" class="delete-image text-2xl cursor-pointer" data-name="'+file.name+'">&times;</span><img class="rounded" src="'+e.target.result+'" ></div>';
            $('#thumb-output').append(img);
        });
        fileReader.readAsDataURL(f);
    }
});

//Remove
$(document).on('click','#deleteImage',function(){
    var pips = $('.img-wrap').toArray();
    var $selectedPip = $(this).parent('.img-wrap');
    var index = pips.indexOf($selectedPip[0]);

    var dt = new DataTransfer();
    var files = $("#fileInput")[0].files;

    for (var fileIdx = 0; fileIdx < files.length; fileIdx++) {
        if (fileIdx !== index) {
            dt.items.add(files[fileIdx]);
        }
    }

    $("#fileInput")[0].files = dt.files;

    $selectedPip.remove();
});

//Check current files
$(document).on('click','#showFiles',function(event){
    event.preventDefault();
    var data = $('#fileInput')[0].files; //this file data
    const fileListArr = Array.from(data);
    var fileName = $(this).data("name");

    for(i = 0; i < fileListArr.length; ++ i){
        console.log(fileListArr[i]);
    }
});

</script>

Upvotes: 0

Luca Filosofi
Luca Filosofi

Reputation: 31173

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...

Upvotes: 1

arun bahal
arun bahal

Reputation: 338

Try with this below code, I have changed all id attribute to class attribute because you can't make same id for different elements. Id is always unique.

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/>", {class: 'delete-icon', src: 'x.png', alt: 'delete'}).click(function() {
			$(this).closest(".filediv").remove();
		}));
	}
   	$(this).closest(".filediv").after($("<div/>", {class: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', class: '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;
}

.delete-icon{ 
    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 class="filediv">
        <input name="file[]" type="file" class="file"/>
    </div><br/>	
    <input type="submit" value="Upload File" name="submit"/>
</form>

Upvotes: 0

BobbyTables
BobbyTables

Reputation: 4685

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

Upvotes: 1

Related Questions