jQuery Thumbnail Preview of Image using FileReader | Lessoncup Programming Blog

Friday, 3 January 2014

jQuery Thumbnail Preview of Image using FileReader

Hi, i got few requests from readers how to display the thumb image before upload and today i am going to tell you about showing the Thumb Image before upload using fileReader we have seen this feature in many websites like twitter and facebook and i have done this using HTML5 FileReader API and jQuery it is just few lines of code, let's see how we do this.


HTML

in html take the input file type and image tag to display the image thumb
<div class="lessoncup">


<h1>jQuery Thumbnail Preview of Image</h1>

<form action="" method="post" enctype="multipart/form-data" id="imageuploadFrom">

<input name="image" type="file" class="image" id="image" multiple><br/>

</form>

<img class="prevImg" src="">


</div>

JAVASCRIPT

now write the change function on #image as a selector and take the image content by using getElementByID() method now create a new FileReader() Class and use the readAsDataURL() method to render the image data and display the thumb with onLoad function in image tag $('.prevImg').attr('src',e.target.result).fadeIn();
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>

<script>

$(document).ready(function(){


 $("#image").change(function(){
  
  var file = document.getElementById("image").files[0];

  var readImg = new FileReader();
  
  readImg.readAsDataURL(file);
  
  readImg.onload = function(e) {
   
   $('.prevImg').attr('src',e.target.result).fadeIn();
   
   }
   
  })
  
  
})

</script>

Live Demo   Download Script

3 comments :

  1. how to implement a fadeIn effect to load images one by one, like fadeIn image for image in multiple images

    ReplyDelete
  2. Multiple Images:
    http://jsfiddle.net/qF7Ff/1/

    ReplyDelete
  3. Awesome tutorial dude! Thankyou very much. This helped me alot.

    ReplyDelete

Mohammad Khasim
Blogger | Web Developer
Hyderabad - INDIA
lessoncup@gmail.com

PHP | My SQL | JQUERY
Web Development Tools | CMS | Frameworks | SEO

Get my Latest Lessons