Search code examples
javascriptjqueryhtmlfile-uploadmultiple-file-upload

How to add/remove button for multiple uploaded files?


I want to add remove button for remove image thumbnail and selected file. How can i do it? This is my code

Js:

window.imagePreview = function (t) {
    if (t.files && t.files[0]) {
        for (var i = 0; t.files.length >= i; i++) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#image-preview').append('<img src="' + this.result + '"/>');
            };

            reader.readAsDataURL(t.files[i]);
        }
    }
}

CSS:

.btn-file{
    position: relative;
}
.btn-file input[type=file] {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    opacity: 0;
}

#image-preview {
    width: 100%;
    max-height: 260px;
    height: 260px;
    overflow-y: auto;
    background-color: #F0F0F0;
    border: 1px dashed #928f8f;
    border-radius: 4px;
    margin-bottom: 10px;
}


#image-preview img {
    max-width: 120px;
    max-height: 120px;
    display: inline-block;
    margin: 5px;
}

HTML:

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="image-preview"></div>
  <span class="btn btn-primary btn-file">
    <input type="file" name="file[]" id="file" class="" multiple onchange="imagePreview(this)" style="width: 0;height: 0;">
      Select Files
  </span>

JSfiddle

And how fix this error:

Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'


Solution

  • Check out this code see if it is what you want.

    window.imagePreview = function (t) {
        if (t.files && t.files[0]) {
            for (var i = 0; t.files.length > i; i++) {
                var reader = new FileReader();
                reader.onload = function (e) { 
                    var thumbnail = '<div>';
                        thumbnail += '<img class="image" src="' + e.target.result + '"/>';
                        thumbnail += '<button class="removeButton">Remove File</button>';
                        thumbnail += '</div>';
                    $('#image-preview').append(thumbnail); 
    
                    $(".removeButton").on("click", function(){
                       $(this).closest('div').remove();
                       document.getElementById("file").value = "";
                    });
    
                };
                reader.readAsDataURL(t.files[i]);
            }
        }
    }
    

    By the way, the error you got is because you set t.files.length >= i, which cause the loop runs one more time and the last time it runs there is no file data available.

    JSfiddle