Preview an image before uploading

Sunday, 15th October 2017


This tutorial uses Filereader object to display the images that the user selected. Filereader object lets web application asynchronously read the content of the files stored on the local computer.

To preview an image, we need some space to display the image and a input to select the image. Let's define a img tag with id preview and an input tag of type file with id imageFile.

	<img src="" id="preview" alt="Preview" height=200px width=500px/><br/>
	<input type="file" id="imageFile" onChange="previewImage();"/>

Whenever the content of input tag changes it calls the javascript function previewImage. This function displays the image that the user selected.

The previewImage function is defined as follow:

	function previewImage() {
		var imageFile=document.getElementById("imageFile");
		var file=imageFile.files[0];
		var reader=new FileReader();
		reader.onload=function(e) {

This function works as follow:
it takes reference to the input element. Define a new Filereader object. Using this object and method readAsDataURL read the content of the file. We define a event handler using Filereader.onload property. This event handler is executed when the load event is fired, when content read with readAsDataURL is available. This event handler set the src attribute of img tag.

Have anything to add or need help, just ping

Remember "Sharing is Caring"

Managed WordPress Hosting Static New


Thank You...

request failed! Contact admin.

Search Your Domain Name Here

WordPress Hosting Offer July