Image Preview Thumbnails before upload using jQuery & PHP

If you are creating an image uploader, you can provide thumbnail preview of currently selected images in file input field. We don’t need to upload entire file to server to do that. File API is supported by all modern browsers, we just need to take advantage of this feature, it provides us with information about files and allows to access their content.

Mark UP

Let’s start by dropping HTML code within the body of the page. HTML contains an input field and a DIV element which will output the thumbnails.

1
2
<input type="file" id="file-input" multiple />
<div id="thumb-output"></div>

jQuery

When user selects file for upload, we will make sure user browser supports File API, and then we loop though all queued files reading their contents and appending them to the output element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$(document).ready(function(){
    $('#file-input').on('change', function(){ //on file input change
        if (window.File && window.FileReader && window.FileList && window.Blob) //check File API supported browser
        {
            $('#thumb-output').html(''); //clear html of output element
            var data = $(this)[0].files; //this file data
           
            $.each(data, function(index, file){ //loop though each file
                if(/(\.|\/)(gif|jpe?g|png)$/i.test(file.type)){ //check supported file type
                    var fRead = new FileReader(); //new filereader
                    fRead.onload = (function(file){ //trigger function on successful read
                    return function(e) {
                        var img = $('<img/>').addClass('thumb').attr('src', e.target.result); //create image element
                        $('#thumb-output').append(img); //append image to output element
                    };
                    })(file);
                    fRead.readAsDataURL(file); //URL representing the file's data.
                }
            });
           
        }else{
            alert("Your browser doesn't support File API!"); //if File API is absent
        }
    });
});

CSS

Finally using CSS we need to scale down images output, because the images are still full size and giving them new width or height will resize images to thumbnail version.

1
2
3
4
.thumb{
    margin: 10px 5px 0 0;
    width: 100px;
}

Demo

    Message Type : Question Comment ?
    • Question : Can include code, jsFiddle, codePen etc using Markdown Syntax.
    • Comment : Short comments and questions.