Create Thumbnail Preview of Images Using HTML5 API

Now, with the help of HTML5, web developer can create thumbnail preview of images that a user may wish to upload to remote server. You can check out the demo, if you are still not clear about it.

View Demo

Getting Started

The HTML5 API that we are going to use is ‘File API’. This API provide several interfaces for us to access a file from local file system.

  • File: Provides information such as, name of the file, size, and mimetype.
  • Blob: Which allows slice a file into byte ranges.
  • FileList: A collection / array of file objects.
  • FileReader: An interface can be used to read the information from the the images.

In this tutorial, we are going to mainly cover interface of FileReader at the moment, and we will talk about the rest in the upcoming tutorial.

Ok, before we start, the first thing we need to do is to check whether the browser has the capability to support FileReader:

 <script type="text/javascript"> 
 if (window.FileReader) { 
 	//then your code goes here 
 } else { 
 	alert('This browser does not support FileReader'); 
 }
 </script>

After that, let’s insert the file upload and the output of thumbnail into the HTML structure as shown below:

<input type="file" id="files" />
<br />
<output id="list"></output>

The next thing is to add an event listener, to run a thumbnail generating function every time, when we re-selecting new images to upload.

document.getElementById('files').addEventListener('change', handleFileSelect, false);

Now, let’s construct the thumbnail generating function – ‘handleFileSelect’.

function handleFileSelect(evt) { 
	var files = evt.target.files; 
	var f = files[0]; 
	var reader = new FileReader();
	reader.onload = (
		function(theFile) { 
			return function(e) { 
				document.getElementById('list').innerHTML = [
					'<img src="', e.target.result,'" title="', theFile.name, '" width="50" />'
					].join("); 
			}; 
		}
	)(f);
	reader.readAsDataURL(f); 
}

As you seen above, we captured the targeted file upload via the parameters ‘evt‘ sent from event listener that we defined earlier, and accessing the information of targeted images via FileReader, and lastly calls reader.readAsDataURL() render the image into thumbnail by setting the ‘src’ attribute to a data URL.

That’s it!

View Demo

More HTML5 Web Development Tutorial?

Check out the complete list of onlyWebPro’s HTML5 Web Development tutorial here!


Posted

in

by

Advertisement