Filereader API and HTML 5 to display images in forms

So,  recently  I was working on creating a HTML form for users to register for a website and being no expert on HTML I ran across multiple issues. Most of them were fairly trivial and could be easily solved by reading through HTML, javascript and PHP help or searching the internet, but one of them stood out. I wanted to provide a form that allowed users to upload images (self), but I did not want to store the images on the server until they submit the whole form. There are multiple articles on how to upload the images into a temporary folder on the server and then display them or use one of the many available services, but not a very a clear article on how to do just read and display the image on the client itself.

It is only then that I came across this tutorial that a HTML 5 file reader API even  existed. I have just tweaked this tutorial for my needs to allow the browser to read the selected file and display it in the form itself before the form is submitted. My simple form does not provide additional image services (like cropping, resizing etc) , but those are easily available using either of the following services that  I came across: webresizer.com or aviary.com that provide easy integration APIs.

<!DOCTYPE html>
<html>
	<head>
		<title>Test File Upload </title>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
		<link rel="stylesheet" type="text/css" href="./testFile.css"></link>
	</head>
	<body>
		<form method="post" action="" enctype="multipart/form-data">
			<div id="li_photo" class="imageuploader" >
					<label class="description" for="element_photo" class="element_7">Upload a Photo:</label>
					<input id="element_photo" name="element_photo" class="file" type="file" accept ="image/gif,image/jpeg,image/png"/>
					<div id="dropbox">
						<span class="message">Image Preview<br /></span>
					</div>       			
			</div>
			<div class="buttons" >
					<input id="saveForm" class="button_text" type="submit" name="Submit" value="Submit"/>
					<br/><br/>
			</div>
		</form>
		<script type="text/javascript" src="./test.js"></script>
	</body>
</html>

The java script is shown below:

var dropbox = $('#dropbox'),
		message = $('.message', dropbox);
	
	

var template = '<div id="template">'+
						'<span class="imageHolder">'+
							'<img />'+
							'<span></span>'+
						'</span>'+
					'</div>'; 

jQuery('#element_photo').change(
	function() {
		// This starts
		if(this.files!=undefined) {
			createImage(this.files[0]);
		}
		else {
			showMessage('Your Browser does not support HTML5 uploads! Cannot show preview!');
		}
	}
);
	
	
function createImage(file) {

   		var preview = $(template), 
			image = $('img', preview);
			
		var reader;
		try
		{
			reader = new FileReader();
			var max_file_size = 1048576 * 2;
			if (file.size > max_file_size) {
				showMessage('File size is too big, limit under 2MB');
				return;
			}
			if($('#template') !=[]) {
				$('#template').remove();
			}
		} catch (err) {
			showMessage('Your Browser does not support HTML5 uploads! Cannot show preview!');
			return;
		}
			
		
		reader.onload = function(e){
			
			// e.target.result holds the DataURL which
			// can be used as a source of the image:
			
			image.attr('src',e.target.result);
			image.attr('width','192');
			image.attr('height','192');
		};
		
		// Reading the file as a DataURL. When finished,
		// this will trigger the onload function above:
		reader.readAsDataURL(file);
		
		message.hide();
		preview.appendTo(dropbox);
		
		// Associating a preview container
		// with the file, using jQuery's $.data():
		$.data(file,preview);
}

function showMessage(msg) {
		message.html(msg);
}

The createImage function in the script uses the File Reader API to read the image file which is then displayed on to the page. A working link with the example can be found at fileupload.thechimerical.kodingen.com (Try out kodingen.com for easy prototyping and testing). You can download the actual files from the BOX folder.

The FileReader API is a HTML5 API that does not work on all the browsers (IE9, and Safari 5.1.7 don’t support it yet) while it works like a charm on Chrome and Firefox on both MACs and Windows. One note about Chrome is that the FileReader API will throw a Security exception if you try and test the scripts using this API on a local folder using file:/// access (Mozilla is more lenient).

One response to “Filereader API and HTML 5 to display images in forms

  1. Great! But how to use it with multiple file input in a form?

Leave a Reply

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

WordPress.com Logo

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