I have been working for sometime now on HTML5 with Image preview and upload functionality.Sometimes back I had tried to implement the image preview functionality on the client side using the JavaScript without HTML5 and had been having really hard time making the code work across all browser without tweaking the browser setting on the client side.I would say its impossible without a some kind of flash plugin or java applet to implement this functionality given that lot of browsers just blocks the script access to the input file src tag unless someone is extremely intelligent programmer.I had written about this earlier over here.Finally I gave up that approach and decided to have graceful fallback approach using both HTML5 and input file type by using the object detection feature of the browser.
HTML 5 has somewhat cool features when it comes to File API.With File API’s we can now have all the information as what is required to make the File preview functionality complete.Using HTML5 File Api,one can easily know the file name,file size and if required the file last modified date as well.Below is the rough code,which will give you some ideas as how to preview the image before uploading it in the server,
<!DOCTYPE HTML>
<html>
<head>
<meta charset=”utf-8″>
<script type=”text/javascript”src=”js/checkbrowser_01.js”>
</script>
<title>HTML 5 Image Preview</title>
</head>
<body>
<label>Upload your Image:</label>
<input name=”imguploader” type=”file” multiple=”" accept=”image/jpeg”
id=”idimgup” title=”Imageuploader” onChange=”previewimage1()”/>
<br></br>
<input name=”Submit” type=”button” class=”clbtnpreview” id=”idbtnpreview”
title=”Preview” onClick=”previewimage()” value=”Preview”/><br></br>
<div>
<img name=”DemoImage” src=”" id=”idimg” width=”400″ height=”400″
alt=”Demo Image” style=”background-color: #00FFFF”/>
</div>
</body>
</html>
In the above code,checkbrowser js file has below function which will take the image path and show it for preview by reading data as dataURL of the file reader interface.
imgreader = new FileReader();
imgreader.onload=function(Event){
document.getElementById(“idimg”).src = Event.target.result;
};
function previewimage1(){
if (document.getElementById(“idimgup”).files.length === 0)
{return; }
var File = document.getElementById(“idimgup”).files[0];
imgreader.readAsDataURL(File);
}
If you are using the F12 Developer tools of the browser ,we can clearly see the image path appended to the src of the image using the base 64 encoding.Using this approach one can easily preview the images on any HTML5 File API compliant browsers.
In addition to using FileReader interface for previewing images, we also have a choice of
using createObjectURL method for previewing the images.The code for windows create object URL looks like below,
<!DOCTYPE html>
<html>
<head>
<title>HTML 5 Image Preview Sample</title>
<meta http-equiv=”X-UA-Compatible” content=”IE=9″>
<style type=”text/css”>
span{
align:left;
}
</style>
</head>
<body>
<h1>HTML 5 Image Preview Sample</h1>
<input type=”file” id=”fileSelector” multiple accept=”image/*” />
<div id=”fileContentList” style=”list-style-type: inline-block;”><
br></br></div>
<!– This will be populated with <img> elements via JavaScript. –>
<script type=”text/javascript”>
var infomessage = [];
if (!document.getElementById(‘fileSelector’).files) {
message = ‘<p>The ‘ +
<a href=”http://dev.w3.org/2006/webapi/FileAPI/” target=”_blank”>
File API</a>s ‘ +
‘are not fully supported by this browser.</p>’ +
‘<p>Upgrade your browser to the latest version.</p>’;
document.querySelector(‘body’).innerHTML = infomessage;
}
else {
document.getElementById(‘fileSelector’).addEventListener(‘change’,
handleFileSelection, false);
// Add an onchange event listener for the <input id=”fileSelector”> element.
}
function handleFileSelection(evt) {
var files = evt.target.files; //The files selected by the user
if (!files) {
alert(“<p>At least one selected file is invalid – do not select any folders.</p);
return;
}
// The variable “files” is an array of file objects.
for (var i = 0, file; file = files[i]; i++) {
window.URL = window.URL || window.webkitURL;
var img_element = document.createElement(‘img’); // Select Image file only.
img_element.src = window.URL.createObjectURL(file);.
img_element.width = 400; // Make all images the same width.
img_element.height= 400;// Make all images the same height
img_element.style.verticalAlign = “middle”; //
img_element.style.margin = “4px 4px 4px 0″;
// The file URL is not needed once the file image has been fully loaded.
img_element.onload = function() {
window.URL.revokeObjectURL(this.src);
}
var span_element = document.createElement(‘span’);
span_element.innerHTML = file.name;
var li_element = document.createElement(‘li’);
li_element.style.display= “inline”;
li_element.appendChild(img_element);
li_element.appendChild(span_element);
document.getElementById(‘fileContentList’).appendChild(li_element);
} // for
} // handleFileSelection
</script>
</body>
</html>
If you are using createObjectURL method, then you need to make sure that you account for both windows and webkit objects by using the below code.
window.URL = window.URL || window.webkitURL;
However for some reasons,using the createObjectURL method was not working in Safari 5x and Opera 11x. With Opera 11.60/Safari 5.1(on windows 7) I can see in Dragon Fly/developer’s tools, that opera for some reasons do not identify the window.createURL as an Object and gives you type reference error.So this makes me believe that these 2 browsers has got somewhat partial support for file api though they both claim to support HTML5 file api’s completely.
There is one thing which I noticed while working with both the above codes, from the time I upload the image to the time browser displays the image for rendering, I can feel somewhat pause which was not the case earlier when I did not use HTML5 File API.Seems like I have a bias here.
Overall its good stuff and definitely a step which can enhance the speed of the web and websites.
Technorati Tags: HTML5,FileReader,createObjectURL,ImagePreview.