HTML5 File API Example

Learning By Doing - Here we try to provide some sample codes and links to external resources. There is a lot of HTML5 materials.

Image File Picker

Pick a image / file and upload to server. This sample using File API, FileReader
  1. Trigger a system file picker
  2. Insert the image back to the DOM for review
  3. Send to server

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Zetakey HTML5 Webkit Browser - Sample Codes</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>

  <body>
    <p>This sample use HTML5 file API, review and upload</p>

    <form action="upload_file.php" method="post"
    enctype="multipart/form-data">
      <label for="files">Filename:</label>
      <input type="file" id="files" name="files[]" multiple />
      <br/>
      <input type="submit" name="submit" value="Submit">
    </form>

    <output id="list"></output>

    <script>
      function handleFileSelect(evt) {
        var files = evt.target.files;
        // FileList object

        // Loop through the FileList and render image files as thumbnails.
        for (var i = 0, f; f = files[i]; i++) {

          // Only process image files.
          if (!f.type.match('image.*')) {
            continue;
          }

          var reader = new FileReader();

          // Closure to capture the file information.
          reader.onload = (function(theFile) {
            return function(e) {
              // Render thumbnail.
              var span = document.createElement('span');
              span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
              document.getElementById('list').insertBefore(span, null);
            };
          })(f);

          // Read in the image file as a data URL.
          reader.readAsDataURL(f);
        }
      }


      document.getElementById('files').addEventListener('change', handleFileSelect, false);
    </script>
  </body>
</html>