In this article I will explain with an example, how to show (display) image preview before upload using JavaScript.
 
 

HTML Markup

The HTML Markup consists of:
FileUpload – For selecting image file.
The Fileupload has been assigned with an OnClick event handler.
Div – For displaying live preview.
<input id="fileupload" type="file" onchange="FileSelected(this)" />
<hr />
<b>Live Preview</b>
<br />
<br />
<div id="dvPreview">
</div>
 
 

JavaScript implementation

When a File is selected, a check is performed to determine whether the file is a valid image file using Regular Expressions and then using HTML5 FileReader API, the File selected in the FileUpload control is read as BASE64 string using the readAsDataURL method and is displayed using an Image element.
<script language="javascript" type="text/javascript">
    function FileSelected(fileUpload) {
        var dvPreview = document.getElementById("dvPreview");
        dvPreview.innerHTML  "";
        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
        if (regex.test(fileUpload.value.toLowerCase())) {
            if (typeof (FileReader) !"undefined") {
                var  reader = new FileReader();
                reader.onload = function (e) {
                    var img = document.createElement("img");
                    img.src e.target.result;
                    dvPreview.appendChild(img);
                }
                reader.readAsDataURL(fileUpload.files[0]);
            }
         }else {
            alert("Please upload a valid image file.");
        }
    };
</script>
 
 

Screenshot

JavaScript: Show (Display) image preview before upload
 
 

Browser Compatibility

The above code has been tested in the following browsers.
Microsoft Edge   FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 

Demo

 
 

Downloads