Getting to Grips with the HTML5 File API

The HTML5 File API allows developers to interact with the local filesystem on the client-side. Using these APIs, developers can build more robust web applications that work seamlessly both online and offline. This tutorial demonstrates the basic usage of these APIs to do common tasks like reading the properties and content of files.

Disclaimer – At the time of writing this article, only the latest versions of Chrome, Firefox and Opera support these features.

2. Handle selection of a single file.

The easiest way to load a file is to use a standard method, which allows the selection of a single file only:

<input type="file" id="file" name="file">

Try it:

3. Handle a selection of multiple files.

Simply add the multiple attribute to the input element. The name="files[]" variable stores the list of all selected files. This enables the user to select multiple files in one instance. Note, even though you can select the folders in the dialog box, the browser will ignore them when processing.

<input type="file" id="files" name="files[]" multiple>

Try it:

4. List all of the selected files and their attributes.

The simplest way to implement this, is to attach a listener to the input element and call a function which will attempt to read the properties of each file selected:

5. Drag and Drop mulitple files.

We first create a division as a drop zone where the files will be dropped. Then we attach listeners to both the events – ‘dragover’ and ‘drop’. For the ‘drop’ event we call the function which attempts to read the file properties. The rest of the code, pretty much remains the same.

6. Read a file.

Instantiate the FileReader object, using new FileReader() to read the contents into memory. When the load finishes, the reader’s onload event is fired and its result attribute can be used to access the file data.

Conclusion:

This API can be extended to implement client-side logic to verify the mime-type of the uploaded file, restrict the size of an upload, create a thumbnail preview of images as they’re being sent to the server or allow an app to save a file reference while the user is offline.

When used in conjunction with the above data structures, the FileReader interface can be used to asynchronously read a file through familiar JavaScript event handling and monitor the progress of a read process, catch errors, and determine when the load is complete.

Pankaj Parashar is a front-end designer and web developer from Mumbai, India. He is extremely passionate about the web, constantly looking for new web technologies and aims to make the web a better place to live. He specializes in frontend technologies like HTML5, CSS3, jQuery and knows a thing or two about design as well! He also writes for txpmag.com/people/pankaj-parasha and you can find him on pankajparashar.com and follow his updates@pankajparashar.