HTML5 & JS File API Useage

HTML5 provides us with an easy way to interface with the localfiles using the File API. It can be used offline as well which means that we can generate thumbnail previews without uploading the file to the server! This is just one of the benefits of this API. I am going to give you a walk-through for how you can make a small Meta-data explorer app using the File API.

Our app will have the following features:

  • Allow uploading of more than 1 file
  • Display name, file-type, size and last-modified date of the selected files
  • Provide us with a Drop Zone where we can drop the files to upload them

1.Creating the directories and files

Let’s start off by creating our basic directory layout and files:

$ cd ~/Desktop
$ mkdir fileapi_example
$ cd fileapi_example
$ mkdir css js
$ touch index.html js/main.js css/main.css

The above commands will generate the following directory layout:

.
├── css
│   └── main.css
├── index.html
└── js
    └── main.js

There is just one thing missing over here. For the drop zone functionality we will be using filedropjs. You need to download it and place it in the js folder:

$ cd ~/Desktop/fileapi_example/js
$ wget https://raw.github.com/ProgerXP/FileDrop/master/filedrop-min.js

Now it’s time to add some basic content to the files

2.Adding Content to index.html

Just put the following code in index.html files and let me explain it a bit:

<!DOCTYPE html>
<html>
<head>
  <title>File Metadata!</title>
  <link rel="stylesheet" type="text/css" href="css/main.css">
  
</head>
  <body>
    <div class="selection">
      <fieldset id="zone">
        <legend>Drop a file inside...</legend>
        <p>Or click here to <em>Browse</em>...</p>
      </fieldset>
      <output id="list">
        <h4>Information</h4>
        <ul class="main">No File selected</ul>
      </output>
    </div>
    <script type="text/javascript" src="js/filedrop-min.js"></script>
    <script type="text/javascript" src="js/main.js" /></script>
  </body>
</html>

There is nothing super-fancy here. The <fieldset> tag is taken from the filedrop examples. The <output> tag will show the metadata info about our files. The main magic happens in the main.js file!

3.Updating main.css file

Add the following content to main.css file. This is just basic css to make out app look pretty:

body{
	background: repeat-x left top url("data:image/gif;base64,R0lGODlhNAALAIAAABBQdcHm+SwAAAAANAALAAACK4SPqWvhD6MMrNo2s7xc6f90IgZqo1h+Z5ea69VmLxxvc1Xb95JHO9ODWAoAOw==") #f2f2f2;
}
.selection{
	width: 400px;
	margin: 0 auto;
	margin-top: 6em;
	text-align: center;
}
h4{
	margin-bottom: 0;
    padding-bottom: 20px;
    padding-top: 20px;
    border: 1px dotted black;
    border-bottom: none;
    background-color: #B7B3B3;
    color: white;
}
ul.main{
	text-align: left;
    margin-top: 0px;
    padding: 30px;
    background-color: white;
    list-style: none;
    padding-left: 50px;
    border: 1px dotted black;
    border-style: dashed;
}
ul.item{
	list-style: none;
	margin-bottom: 30px;
	padding-left: 0px;
}
ul.item:last-child{
	margin-bottom: 0px;
}
.f-name{
  word-wrap: break-word;
}
/***
  Styles below are only required if you're using <iframe> fallback in
  addition to HTML5 drag & drop (only working in Firefox/Chrome/Opera 15+).
 ***/

/* Essential FileDrop zone element configuration: */
.fd-zone {
  position: relative;
  overflow: hidden;
  /* The following are not required but create a pretty box: */
  width: 15em;
  margin: 0 auto;
  text-align: center;
}

/* Hides <input type="file"> while simulating "Browse" button: */
.fd-file {
  opacity: 0;
  font-size: 118px;
  position: absolute;
  right: 0;
  top: 0;
  z-index: 1;
  padding: 0;
  margin: 0;
  cursor: pointer;
  filter: alpha(opacity=0);
  font-family: sans-serif;
}

/* Provides visible feedback when user drags a file over the drop zone: */
.fd-zone.over { border-color: maroon; background: #eee; }
html, body {
	height: 100%;
	max-width: 100%;
	width: 100%;
	margin: 0;
}
.selection {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: 0px; 
}
.selection:after {
  content: "";
  display: block;
}
footer, .selection:after {
  height: 30px; 
}
footer {
  background: #105075;
  padding-top: 1px;
  padding-bottom: 15px;
  padding-left: 30px;
  color: white;
  font-weight: bold;
}
footer a{
	color: #B5CFDE;
	transition: all .5s;
}
footer a:hover{
	color: white;
}

That’s it for the styling. Now let’s move on to the main main.js file.

4.Modifying main.js file

We can get metadata info about a file in js by querying the file handler after getting a handle to a file. For instance:

//Name
f.name

//Size
f.size

//Type
f.type

//Last Modified Date
f.lastModifiedDate

Add the following content to our main.js file:

var options = {}
var zone = new FileDrop('zone', options)

// Do something when a user chooses or drops a file:
zone.event('send', function (files) {
  // FileList might contain multiple items.
  // files is a FileList of File objects. List some properties.
  var output = [];
  for (var i = 0, f; f = files[i]; i++) {
  	output.push('<ul class="item"><li class="f-name"><b>Name:</b> ', decodeURIComponent(escape(f.name)), '</li><li><b>Type:</b> ', f.type || 'n/a', '</li><li><b>Size:</b> ',
  		f.size, ' bytes, </li><li><b>last modified:</b> ',
  		f.modDate,'</li></ul>');
  }
  document.getElementById('list').innerHTML = '<h4>Information</h4><ul class="main">' + output.join('') + '</ul>';
})

zone.multiple(true);

This is just simple code. The main crux of this code lies in the send event handler. When a user drops or uploads a file using the upload button, send event is called. Next we loop over each and every file and append it’s meta-data info to the output array. After that we push all of the data from the output array to the #list div. It’s that simple!

The last line:

zone.multiple(true);

tells zone that it should allow multi-file uploads as well.

Congrats on reaching this far! You can see the app running here as well