HTML5

HTML5 File API

With the advent of HTML5 ( the new standard for the web ) also comes new API, with great features. This new set of API has made things that were quite difficult or outrightly impossible to do on the browser, possible.
 
 
 
 
 
 
 
 
 


 
In this example we are going to demystify one of the features of HTML5-The file API. For this example we will use:

  • A computer with a modern browser installed.
  • notepad++.

1. Getting Started

HTML5 File API comes with a lot of possibilities. Operations that were once only possible on native applications, are now a possibility on both desktop and mobile browsers.
The HTML5 File API allows you to create applications that let the user interact with files locally. Basically, you can load files and render them in the browser without actually having to upload the files. It is now possible to display thumbnails of images on the user hard drive in a browser.

1.1 Using The File API

Adding a file chooser dialog to a web app is as simple as adding the line below to your HTML.

< input type =file id=pick >

The input type file is used to add a file chooser dialog to HTML. The attribute id is used to identify an HTML element in a document. To work with files locally, their are three objects we would need to work with.

  • File: A single file object with some metadata. It represents a file object on the system.
  • FileList: Simply a list of file objects. For instance, a list of files inside a directory.
  • FileReader: An object to read files with a number of methods and event handlers to interact with them.

If a user selects more than one file, the filelist object gives us access to each file the user selected. To allow the user select multiple files, add mutiple to the file chooser signature.

< input type =file multiple id=pick >

We need to register an onchange listener to our file chooser.

< input type =file multiple id=pick onchange="change(event)" >

Complete code below

index.html

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:visible;
	padding:0%;
	border:0%;
	}
#pick{
margin:10px;
}
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title> 
Html5 Semantic Elements Example
</title>
	<style>


</style>
	</head>
	<body>
<script>
function change(){
var p=document.getElementById("pick")
var p1=p.files;
alert(p1.length+ " files choosen");

}
</script>
<p>
<input type =file multiple id=pick onchange="change()" >
</p>

	</body>
	</html>

In line 39 we create the file chooser and register an event listener. We also add the attribute multiple to the tag, so as to allow a user select more than one file. When an onchange event occurs the function change is called. In the change function we alert the the number of files that was selected.
If you want the user to select only one file, just remove the attribute multiple from the file chooser tag or run the code below.

index2.html

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:visible;
	padding:0%;
	border:0%;
	}
#pick{
margin:10px;
}
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title> 
Html5 Semantic Elements Example
</title>

	</head>
	<body>
<script>
function change(){
var p=document.getElementById("pick")
var p1=p.files;
alert(p1.length+ " files choosen");

}
</script>
<p>
<input type =file id=pick onchange="change()" >
</p>

	</body>
	</html>

1.2 Handling Multiple Files

You can easily loop through the FileList to access each file object.

for (var i = 0; i<files.length; i++) { 
var file = files[i]; 
//where files represents the FileList object.
 }

There are three attributes provided by the File object that contain useful data about the file.

  • name: The file’s name as a read-only string. This is just the file name, and does not include any path information.
  • size: The size of the file in bytes.
  • MIME: The MIME type of the file as a read-only string or an empty string (“” ), if the type couldn’t be determined.

index3.html

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:visible;
	padding:0%;
	border:0%;
	}
#pick{
margin:10px;
}
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title> 
Html5 Semantic Elements Example
</title>

	</head>
	<body>
<script>
function change(){
var p=document.getElementById("pick")
var p1=p.files;
var c=document.getElementById("w");
var e="Number of files "+p1.length;
for(var i=0; i<p1.length; i++){
var r=p1[0];
e=e+"<p><br>Size Of File: "+r.size + "bytes<br>Name Of File: "+r.name+"<br>Mime Type Of File "+r.type+"</p>";
c.innerHTML=e;
}
}
</script>
<p>
<input type =file id=pick onchange="change()" multiple >
</p>
<div id=w>

</div>
	</body>
	</html>

The above code iterates through the FileList object and prints out the details of each file. In line 29 we get the file chooser object (input type file) and store it in a variable. In 30 we store the FileList object in a variable, in line 31 we store our div object in a variable. In the for loop we iterate through the FileList object and store the details of each file in a variable(as a string) and print the result on the screen.

1.3 Displaying A Picture From Disk

In this section we are going to display picture/s or image/s stored on the user hard drive in the browser. Once the user has selected a file and you have a reference to the selected file (e.g. via the onchange event) you can read the file using a FileReader. The FileReader object contains the following functions, you can use to load files with:

  • readAsText()
  • readAsDataUrl()
  • readAsArrayBuffer()

index4.html

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:visible;
	padding:0%;
	border:0%;
	}
#pick{
margin:10px;
}
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title> 
Html5 File API Example
</title>

	</head>
	<body>
<script>
function change(){
//get the file chooser object
var p=document.getElementById("pick")
//get the div element where the  images will be displayed
pd=document.getElementById("pr");
var p1=p.files;
//get the first file in the list
var p2=p.files[0];
//create a reader object to read the file
var reader = new FileReader(); 
// register an onload object on the reader
reader.onload = function(loadedEvent) { 
e=document.createElement("img"); // create an image element
e.setAttribute("src",loadedEvent.target.result); // set the SRC of the image
e.setAttribute("width","80%"); // set the width of the image
pd.appendChild(e); // add the image 
alert("")
 } 
reader.readAsDataURL(p2);// read the file as a dataUrl

}
</script>
<p>
<input type =file id=pick onchange="change()" >
</p>
<div id=pr>

</div>
	</body>
	</html>

When you select an image, it is displayed in the browser, but you can only select one image at a time.

1.3 Display Text

In the next example, we are going to read text from a text file and display it in the browser.

index4.html

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:visible;
	padding:0%;
	border:0%;
	}
#pick{
margin:10px;
}
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title> 
Html5 File API Example
</title>

	</head>
	<body>
<script>
function change(){
//get the file chooser
var p=document.getElementById("pick")
//get the FileList Object
var p1=p.files;

//create a reader object to read the file
var reader = new FileReader(); 
// register an onload object on the reader
reader.onload = function(loadedEvent) { 
var pd=document.body;
e=document.createElement("div"); // create a div element
e.setAttribute("id","d"); // set the id for the div
e.setAttribute("width","80%"); // set the width of the div
pd.appendChild(e); // add the div
e.innerHTML="<p>"+loadedEvent.target.result+"</p>"

 } 
reader.readAsText(p1[0]);// read the file as a dataUrl
}
</script>
<p>
<input type =file id=pick onchange="change()" >
</p>

	</body>
	</html>

2. Summary

In this example we learnt about HTML5 file API. We also studied about the File, FileReader and FileList objects. We learnt how to read images and text file from the users hard drive and display the contents appropriately in the browser.

3. Download the source code

Download
You can download the full source code of this example here: html5fileapi

 

Olayemi Odunayo

I am a programmer and web developer, who has experience in developing websites and writing desktop and mobile applications. I have worked with both schematic and schemaless databases. I am also familiar with third party API and working with cloud servers. I do programming on the client side with Java, JavaScript, html, Ajax and CSS while I use PHP for server side programming.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button