HTML5 File API

September 27, 2011

Using the HTML5 File API it is possible to get hold of information about files that have been selected in an input type=file before the files are uploaded to the server. You can even look inside the files to see what their content is.

HTML

This example is based on this simple form, that doesn't even have a submit button or target:

<input type="file" name="file" multiple/>

It allows multiple files to be selected by using shift-click.

JavaScript

This javascript loops through the selected files, and outputs their name, size and mime type:

var input = $("input[type=file]");
input.change(function(){
  var files = this.files;

  for (var i=0; i<files.length; i++){
    alert(files[i].name);
    alert(files[i].size);
    alert(files[i].type);
  }
});

File Contents

Once you have a file handle (files[i] in the above code), it's possible to get hold of the contents of the file.

if (files[i].type === 'text/xml'){
  var reader = new FileReader();
  reader.onload = function(e){
    var data = e.target.result;
    console.log(data);
    alert(data);
  };
  reader.readAsText(files[i]);
}

Browser Support

This works in recent Chrome and Firefox browsers. Safari requires 6.0+. Internet Explorer <= 9 doesn't work, there may be support in IE10.

References