Using the HTML5 File API to read the file contents
Friday 14 October 2011
The FileReader API
This API basically lets us read the contents of the file in a number of different ways:
As we are dragging images into the browser, you can check using the file.type which is the file MIME type, the best option is to use the readAsDataURL() which reads the contents of the file and returns it as an encoded URL. The FileReader is basically an asynchronous object so we can use the onload event to work with the file contents.
Thanks to the power of jQuery the code doesn’t become much more complex The whole change is in the jQuery.each() block where we start reading the file and creating an <img> tag instead of just displaying the file name.
And the result looks like this:
As you can see below the image element source is not set to the usual URL but to a data URL that contains all data in a base 64 encoded string.
Using one of the other operations on the FileReader we can get the file contents in a way where we can easily work with it or possibly send it to the server for processing.