Sunday, August 31, 2014

Image upload functionality on client side

Image upload on client side


The main intent of this blog is to show how to read files locally and show the image upload functionality at client side and then it can saved in back end. Using client side functionality will save the call to server and let the user finalize the image first and then on click of Submit may be a call to back end can be sent.

Here is the simple code:
I have taken the help from HTML 5 rocks and created the following code. Its very simple :

<html>
<head>

</head>
<body>
<div ><img id="Uploadedimg" src="" width='100' height='100' alt="no file choosen"  /></div>
<input type="file" id="imgUpload" name="imgUpload">

<script>

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render image.
  document.getElementById('Uploadedimg').src=e.target.result;
 
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }
// set the source of the Image
  document.getElementById('imgUpload').addEventListener('change', handleFileSelect, false);
</script>

</body>
</html>



You are done. The code above is IE 10 and above compliant along with FF and Chrome. I have not removed the loop, you can use the loop to add multiple images using insertBefore.

If you have liked this do comment. Enjoy !!