Show Thumbnail Preview of Image before upload using HTML5 and jQuery

,

In this article I will explain how to show Thumbnail preview of Image before upload using HTML input FileUpload control using jQuery, CSS and HTML5.



The multiple image preview is displayed using HTML5 FileReader API in browsers that support HTML5 i.e. Internet Explorer 10 and 11+, Mozilla FireFox, Google Chrome and Opera.

HTML Markup

<input id="fileupload" type="file" multiple="multiple" /> 
 <h5>Live Preview</h5>
 <br /> 
 <div id="dvPreview">
</div>

jQuery

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(function () {
    $("#fileupload").change(function () {
        if (typeof (FileReader) != "undefined") {
            var dvPreview = $("#dvPreview");
            dvPreview.html("");
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
            $($(this)[0].files).each(function () {
                var file = $(this);
                if (regex.test(file[0].name.toLowerCase())) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var img = $("<img />");
                        img.attr("style", "height:100px;width: 100px");
                        img.attr("src", e.target.result);
                        dvPreview.append(img);
                    }
                    reader.readAsDataURL(file[0]);
                } else {
                    alert(file[0].name + " is not a valid image file.");
                    dvPreview.html("");
                    return false;
                }
            });
        } else {
            alert("This browser does not support HTML5 FileReader.");
        }
    });
});
</script>




Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.