7 out of 12 rated this helpful - Rate this topic

File API

Internet Explorer 10 and Windows Store apps using JavaScript introduce support for File API. File API is a World Wide Web Consortium (W3C) draft web specification for representing file objects in web applications, as well as programmatically selecting them and accessing their data. The File API is currently being standardized by the W3C Web Applications Working Group. By using File API, web developers can access local files on the client machine in a secure way without the need for extensions or plugins.

Smooth file upload experiences

The File API allows a browser or app to read and manipulate files but only if the user provides permission to do so. Additionally, the File API allows for smoother file upload experiences without plugins.

In the following W3C File API example, different code blocks handle progress, error, and success conditions:


function startRead() {
  // Obtain input element through DOM.

  var file = document.getElementById('file').files[0];
  if(file) {
    getAsText(file);
  }
}

function getAsText(readFile) {

  var reader = new FileReader();

  // Read file into memory as UTF-16      
  reader.readAsText(readFile, "UTF-16");

  // Handle progress, success, and errors
  reader.onprogress = updateProgress;
  reader.onload = loaded;
  reader.onerror = errorHandler;
}

function updateProgress(evt) {
  if (evt.lengthComputable) {
    // evt.loaded and evt.total are ProgressEvent properties.
    var loaded = (evt.loaded / evt.total);

    if (loaded < 1) {
      // Increase the progress bar length.
      // style.width = (loaded * 200) + "px";
    }
  }
}

function loaded(evt) {  
  // Obtain the read file data.    
  var fileString = evt.target.result;

// Handle UTF-16 file dump
  if(utils.regexp.isChinese(fileString)) {
    //Chinese Characters + name validation.
  }
  else {
    // Run other charset test.
  }
  // xhr.send(fileString)     
}

function errorHandler(evt) {
  if(evt.target.error.name == "NotReadableError") {
    // The file could not be read.
  }
}


The BlobBuilder API

The BlobBuilder API enables a web developer to manipulate a blob (often equivalent to a file) directly on the client. The BlobBuilder API is defined in the W3C's File API: Writer specification, which is currently in the Working Draft stage.

With File APIs alone, you can read files and use them in different ways within a site; however, you can't directly edit the files in any way unless you upload the file to a server and then download an altered version. With BlobBuilder, you can easily construct a blob (on the client) by simply creating a BlobBuilder object and appending chunks of data to it by calling its append() method. When you're done building your blob, call the BlobBuilder object's getBlob() method to retrieve a blob object containing the data you previously appended to it. The following example (Internet Explorer 10 or later) succinctly demonstrates this process:


<!DOCTYPE html>
<html>

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  <title>Saving Files Locally</title>
</head>

<body id="bodyElement">
  <h1>Saving Files Locally</h1>
  <script>
    function requiredFeaturesSupported() {
      return ( BlobBuilderSupported() && msSaveOrOpenBlobSupported() );
    }
    
    function BlobBuilderSupported() {
      if (window.BlobBuilder) {
        // No change needed - the W3C standard API will be used by default.
      } 
      else if (window.MSBlobBuilder) {
        window.BlobBuilder = window.MSBlobBuilder;
      }
      else if (window.WebKitBlobBuilder) {
        window.BlobBuilder = window.WebKitBlobBuilder;
      }
      else if (window.MozBlobBuilder) {
        window.BlobBuilder = window.MozBlobBuilder;
      }   
      else {
        document.getElementById('bodyElement').innerHTML = "<h1>The BlobBuilder API is not supported - try upgrading your browser to the latest version.</h1>";
        return false;
      } // if-else
      
      return true;
    } // BlobBuilderSupported
    
    function msSaveOrOpenBlobSupported() {
      if (!window.navigator.msSaveOrOpenBlob) {
        document.getElementById('bodyElement').innerHTML = "<h1>The msSaveOrOpenBlob API is not supported - try upgrading your version of IE to the latest version.</h1>";            
        return false;
      }
      
      return true;
    } // msSaveOrOpenBlobSupported
        
    if (requiredFeaturesSupported()) {
      var builderObject = new BlobBuilder(); // Create a blob builder object so that we can append content to it.
      
      builderObject.append("I scream, you scream, we all scream for ice scream."); // Append some content to the builder object.
      window.navigator.msSaveBlob(builderObject.getBlob(), 'msSaveBlob_testFile.txt'); // Move the builder object content to a blob and save it to a file - buildObject is now devoid of any content.
      alert('File saved using msSaveBlob() - note the single "Save" button below.');
      
      builderObject.append("Before you insult a person, walk a mile in their shoes. That way, when you insult them, you'll be a mile away - and have their shoes."); // Appending to a cleared buildObject due to the prior builderObject.getBlob() call.
      window.navigator.msSaveOrOpenBlob(builderObject.getBlob(), 'msSaveBlobOrOpenBlob_testFile.txt'); // Now the user has the option of clicking the Save button and the Open button.
      alert('File saved using msSaveOrOpenBlob() - note the two "Open" and "Save" buttons below.');      
    }
  </script>
</body>

</html>


Be aware that when the MSBlobBuilder object's getBlob() method is called ("builderObject.getBlob()" above), it clears the contents of the builder object (that is, "builderObject" is cleared). Currently, this is true for MozBlobBuilder as well, but is not true for WebKitBlobBuilder. In the WebKitBlobBuilder case, the content associated with the builder object remains after getBlob() is called.

The msSaveBlob() and msSaveOrOpenBlob() methods allow a user to save a blob (that is, a file) to the user's computer as if the file were downloaded from the web. These files are saved to the Downloads folder. Note that the difference between msSaveBlob() and msSaveOrOpenBlob() is that the msSaveBlob() method only provides a Save button to the user, whereas the msSaveOrOpenBlob() method provides both a Save and an Open button. Running the above sample code (in Internet Explorer 10 or later) should help to make this clearer.

Other Improvements

Other file related improvements include multiple file uploads (4 GB per file) with file type filtering. In the following example, multiple Graphics Interchange Format (GIF) or JPEG files can be selected by the user:


<input type="file" name="pic" multiple accept="image/gif, image/jpeg" />

For more information, see the "File Upload state (type=file)" section of the HTML5 specification.

API Reference

File API

Samples and tutorials

How to manage local files

Internet Explorer Test Drive demos

BlobBuilder
Binary File Inspector

IEBlog posts

New Blob Constructor in IE10
Creating Files through BlobBuilder
HTML5, Site-Ready and Experimental
Working with Binary Data using Typed Arrays

Specification

File API
File API: Writer

Related topics

Get Loaded with the File API

 

 

Build date: 4/8/2013

Community Additions

ADD
© 2013 Microsoft. All rights reserved.