SoftwareNerd SoftwareNerd - 2 months ago 14
jQuery Question

How to provide a Preview For Multiple images selected in fileuplaod Using Jquery?

Hi all i have an fileuplaod where user can select multiple images nad i want to show the preview for those selected images before upload...at present i manged it for the single image preview how can i provide preview for the multiple images selected

function readURL(input) {
var img = $(input).closest('div').find('img').first();
var imgid=$(img).attr('id');
if (input.files && input.files[0]) {
alert(input.files);
alert(input.files[0]);
var reader = new FileReader();

reader.onload = function (e) {
$("#"+imgid)
.attr('src', e.target.result);
};

reader.readAsDataURL(input.files[0]);
}
}

<input type="file" accept="gif|jpg|jpeg|png" name="files[]" multiple onchange="readURL(this);" />

<img src="http://placehold.it/140x140" class="img-rounded" id="thumbnailimage">


can any one help here please...

Answer

Ok, here is a really crude implementation

The basic idea is, get the files array, loop through it, use the File API to add images where the src value is that blob which js gives you to play with, rather than the path on the users machine.

var inputLocalFont = document.getElementById("image-input");
inputLocalFont.addEventListener("change",previewImages,false); //bind the function to the input

function previewImages(){
    var fileList = this.files;

    var anyWindow = window.URL || window.webkitURL;

        for(var i = 0; i < fileList.length; i++){
          //get a blob to play with
          var objectUrl = anyWindow.createObjectURL(fileList[i]);
          // for the next line to work, you need something class="preview-area" in your html
          $('.preview-area').append('<img src="' + objectUrl + '" />');
          // get rid of the blob
          window.URL.revokeObjectURL(fileList[i]);
        }


}