How to preview image before uploading with JQuery
Here in this article I will show you How to preview image before uploading with Jquery few line of code. It is best practice to preview image to user he has selected, it will avoid user mistakes of selecting different image and visually it looks good.
Basically we will have to write our code on Change event of file input. which means when ever user changes image the preview will be changes and there will be no page reload, it will happen in no time.
Click the following button to view live demo of how to preview image
Demo of Image Preview
As code is just few lines so I will include whole page code here.
txtFile is id of file input
imgPreview is id of img tag where we have to preview image
Jquery code id written at end of body tag.
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<!DOCTYPE html> <html> <head> <title>Image Preview</title> <style> #imgPreview{ padding:5px; background:#FFF; border:1px solid #DDD; margin:10px; max-height:300px; max-width:300px; } </style> </head> <body> <h1>An Example to preview Image before uploading</h1> <div style="text-align:center;"> <img id="imgPreview" alt="image preview" /> </div> <form action="" method="POST" enctype="multipart/form-data"> <label for="txtFile">Select Image</label> <input type="file" id="txtFile" /> </form> <!--Jquery library--> <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script> <!--Jquery My custom code--> <script> $(function(){ $('#txtFile').change(function(){ if ($(this)[0].files && $(this)[0].files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#imgPreview').attr('src',e.target.result); } reader.readAsDataURL($(this)[0].files[0]); } }); }); </script> </body> </html> |
Comments