How to Show an image preview before uploading to the server via jquery

Hi, In this tutorial, I am going to show you how to see the image preview before uploading into the server by using the javascript. Here you need to load the jquery.js file to the HTML page. after that write the form code related to the image uploading code like this
<form>  
   <div class="form-group">  
    <img id="upImg" src="http://placehold.it/200x200" alt="your image" width="200" height="200" />  
   </div>  
   <div class="form-group">  
    <input type='file' id="imgInp" class="form-control" />  
   </div>  
 </form> 
Here image tag is taken by the purpose of showing the image preview before uploading to the server. Add the below jquery code
<script type="text/javascript">  
   function readURL(input) {  
        if (input.files && input.files[0]) {  
        var reader = new FileReader();  
        reader.onload = function (e) {  
        $('#upImg').attr('src', e.target.result);  
        }  
        reader.readAsDataURL(input.files[0]);  
        }  
        }  
        $("#imgInp").change(function(){  
        readURL(this);  
   });  
 </script>  
When an image is uploaded, It will calls the change function and reads the uploaded image data and push it into the web page display section. Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff


EmoticonEmoticon