Preview image before uploading to server

Here this article explains how to preview an image before uploading on thr server side in jQuery
Using HTML 5 FileReader() we can able to preview the image before uploading it in jQuery.

View DEMO

With jQuery

Step 1 HTML Markup

Lets set up the environment to upload image and preview image.
Here we have added a input file tag and a div. this div tag is used as holder for image ie. preview image before uploading to server.

 


 

Step 2 jQuery Code

Before writing code we need to add a jQuery library file

Next here we bind a change event to our input file tag, and then will check for browser support HTML5 FileReader method, if not then we throw an error.

 

Without jQuery

Step 1 HTML Markup

As we have done earlier, the first we setup environment to upload and preview image. Here am adding one < input > tag with file as type and one image (< img >) tag to preview selected image.






Step 2 javascript code

In this javascript code I used 6 steps

  1. initializing the fileTag variable with ids
  2. checking for non empty fileTag variable
  3. calling the function if there is a change in fileTag
  4. checking for the presence of file
  5. declaring object for FileReader()
  6. setting the attribute src
             var fileTag = document.getElementById("photo"),
			    preview = document.getElementById("previewHolder");
			 if(fileTag){ 
			fileTag.addEventListener("change", function() {
			  changeImage(this);
			});
		}

			function changeImage(input) {
			  var reader;

			  if (input.files && input.files[0]) {
			    reader = new FileReader();

			    reader.onload = function(e) {
			      preview.setAttribute('src', e.target.result);
			    }

			    reader.readAsDataURL(input.files[0]);
			  }
			}

see Multiple image previews before uploading to server