In this tutorial we’ll learn How to Show an image preview before upload in jquery, Showing image before upload is quite easy after HTML release File API , which allows you to create applications that let the user interact with files locally, That means you can upload file and read file data locally and render in browser. It is good idea to display image preview before upload , It feels users that he/she is going to upload right file.
Below is a quick example of the FileReader class to read an image as DataURL and renders a thumbnail by setting the src attribute of an image tag to a data URL.
HTML
JavaScript + Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">script> <script> $(function() { $("#file").change(function () { readImgPath(this); }); // read image path function readImgPath(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#img').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } }) script> |
Above function readImgPath will read image as DataURL and render image source to display thumbnail.
See live demo and download source code.