Saturday, November 21, 2015

Instant Image Preview in the Browser using JQuery

We can set an image element(<img/>)'s value with that of an image we just selected from a file input instantly(without uploading to server) using JQuery.

Suppose we have a form:
<form id="sample_form">
     Photo: <input type="file" id="photo"/>
     <img id="photo_preview" src="#" width="200px"/>
</form>


In order to read the input image and display it in the '<img/>' element, we need to bind the '<input />' element's  '.change' event with a custom JQuery function :
<script>
     $("#photo").change(function(){
         read_file(this);
     });
</script>


Now the function read_file() can be written like this:
function read_file(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
         reader.onload = function (e) {
            $('#photo_preview').attr('src', e.target.result);
         }
         reader.readAsDataURL(input.files[0]);
    }
}

Here is the complete code:
image_preview.html
<!DOCTYPE html>
<html>
 <head>
  <title>Image Preview</title>
  <meta charset="utf-8">
 </head>
 <body>
  <div class="container">
    <form id="sample_form">
       Photo: <input type="file" id="photo"/>
       <img id="photo_preview" src="#" width="200px"/>
    </form>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script>
   function read_file(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#photo_preview').attr('src', e.target.result);
          }
        reader.readAsDataURL(input.files[0]);
      }
    }
  </script>
  <script>
     $("#photo").change(function(){
         read_file(this);
     });
  </script>
 </body>
</html>
Now whenever you browse and select an image, it will be shown instantly in the browser.

No comments: