Preview an image before it is uploaded using JS

Hi,

My colleagues many times asked this question. So i am sharing a simple method to achieve this.

HTML

<form id="form1">
   <input id="filePic" type="file" />
   <img id="imgPic" src="#" alt="" />
</form>

Javascript

function SetImage(fileInput, imgCtrl) {
   if (fileInput.files && fileInput.files[0]) {
       var reader = new FileReader();
       reader.onload = function (e) {
           imgCtrl.attr('src', e.target.result);
       }
       reader.readAsDataURL(fileInput.files[0]); 
   } 
}

$("#filePic").change(function (e) {
   SetImage(this, $("#imgPic"));
});
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s