Using file inputs at the client side

HTML has always lacked a convenient method to read the user's files. Before HTML5, the only way to access user files on the client side was to use an input element of type file, upload that file to the server then send it back to the browser.

HTML5 brings the ability to read user files locally, inside the user's browser using JavaScript code. The implementation is an extension of the functionality of a file input element with additional API.

In this recipe, we're going to display a text file that is selected by the user by using the new HTML5 file API (http://www.w3.org/TR/FileAPI/).

How to do it...

Let's write the code.

  1. Create an HTML page with a file input field and a content div to show the contents of the selected file:
    <!DOCTYPE HTML>
    <html>
      <head>
        <title>File API example</title>
      </head>
      <body>
        <input type="file" id="file" value="Choose text file">
          <div id="content"></div>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
            <script type="text/javascript" src="example.js"></script>
      </body>
    </html>
  2. Then we're going to add the code to read the selected file in example.js:
    $(function() {
      $("#file").on('change', function(e) {

    We can read the selected file from the input element's files property.

      for (var k = 0; k < this.files.length; ++k) {
        var f = this.files[k];
  3. To read the contents, we use a FileReader object. We need to instantiate it, tell it what file to read (and in what way it should read it depending on its type), then attach an event listener when the reading completes that will access the file contents. This is done as follows:
      var fr = new FileReader();
        if (f.type && f.type.match('image/.+'))
          fr.readAsDataURL(f);
        else
          fr.readAsText(f);
  4. By the time the onload function is called, the variable f will change to be set to the value of the last file for each of the onload calls. To avoid this, we capture the variable using an anonymous function pattern.
      (function(f) {
        fr.onload = function(e) {
  5. The listener is called with an event, which in its target property contains our result or the text of the whole file.
      if (f.type && f.type.match('image/.+'))
        $("<img />").attr('src', e.target.result)
        .appendTo("#content");
      else
        $("<pre />").text(e.target.result)
        .appendTo("#content");
      }
      }(f));
      }
      });
    });

How it works...

The HTML5 file API consists of two new additions:

  • The file input element has a files property which contains a list of the selected files.
  • A new type of object called FileReader exists that allows us to read the selected files in different ways by using its methods. Among others there are readAsBinaryString, readAsText, readAsDataURL, and readAsArrayBuffer. It also provides us with event listeners, which we can set to get the file contents when it is loaded or when an error occurs.

To display the text file, we use the reader's readAsText property. As a result, the file data is provided to the onload listener of the reader. The content of the file is a simple string that we append to the div content inside an element that displays preformatted text.

For retrieving images, we call readAsDataURL, and then easily create a new image element whose src attribute is set to that data URL. Then we add this element inside the content div.

If a folder is selected our recipe will display the entire contents of the folder, both text and images.

There's more...

Its possible to specify filters for the file selection dialog, which limits the category of the file. For example, adding accept="image/*" will tell the browser that the input expects images of any type, while adding accept="image/jpeg" will tell the browser that the input expects only JPEG images. This filter is based on media types. More information about available media types can be found at http://www.iana.org/assignments/media-types.

Note

Although IE9 supports a lot of HTLM5 features, the HTML5 file API is not supported. Support was added in IE version 10.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.235.176