Using File API to generate thumbnail for image

HTML5 provides a easy and standard way to interact with local files using File API. This file api could be used to generating image preview as thumbnail before sending to server or other file manipulation such as restricting size of file size , checking file extension on the basis of mimetype.

To check that whether your browser support for file api, we can use this java script snippets as suggested by Eric Bidelman in this article:
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');

In this post I am going to describe how to generate image thumbnail on web browser. So, firstly our html part, in which we have one input file type tag and a image element.

<input id="src" type="file" onchange="fileChange()" /> 
<img id="target" />

Then our java script part in which our script is written for reading file and display it as thumbnail.


function fileChange(){
var src = document.getElementById("src");
var target = document.getElementById("target");

function showImage(src,target) {
var fr=new FileReader();
// when image is loaded, set the source of the image on the image element
fr.onload = function(e) { target.src = this.result; };
// fill fileReader object with image data

At this point we are able to read image from file and display it on client side.
For more information on file api.


Leave a Reply

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

You are commenting using your 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