Export (0) Print
Expand All

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 Blob constructor

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

In older versions of the File API, you could read files, but you couldn't directly edit them in the client. You could make changes to a representation of a file, but to save those edits required uploading the file and the edits to a server, processing it all on the server, then downloading the altered file. With the Blob constructor, you can easily create a Blob from an array. The array can include other Blob objects, text strings, or array buffers, and you pass the array into the blob as a parameter when you create it.

An optional dictionary object can be added as a second parameter, and can include two members: type and endings.

The following example (for 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>
  <h1>Saving Files Locally</h1>
  <script>
    //check for Blob availability
    if (typeof Blob !== "undefined") {
      demoBlobs();
    } else {
      //your fallback code here
    }

    function demoBlobs(){  
      //create a Blob with an array and the optional dictionary object.
      var blob1 = new Blob(
        ["There are 10 kinds of people ", "in the world.\r\n"], //array
        { type: "text/plain", endings: "native" } //dictionary object
      );

      //create a second blob that uses the first blob in its array
      var blob2 = new Blob([blob1, "Those who understand binary and those who don't."]);

      // Save the blob1 content to a file, giving just a "Save" option
      window.navigator.msSaveBlob(blob1, 'msSaveBlob_testFile.txt'); 
      alert('File saved using msSaveBlob() - note the single "Save" button below.');
  
      // Save the blob2 content to a file, giving both "Save" *and* "Open" options
      window.navigator.msSaveOrOpenBlob(blob2, 'msSaveBlobOrOpenBlob_testFile.txt'); 
      alert('File saved using msSaveOrOpenBlob() - note the two "Open" and "Save" buttons below.');
    }
  </script>
</body>

</html>


The msSaveBlob() and msSaveOrOpenBlob() methods allow a user to save the Blob to the user's computer as if it was a file they downloaded from the web. The files are saved to the Downloads folder by default.

The difference between msSaveBlob() and msSaveOrOpenBlob() is that the msSaveBlob() method only provides a Save button to the user. The msSaveOrOpenBlob() method provides both a Save and an Open button. Running the above sample code (in Internet Explorer 10 or later) should 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

Related topics

Get Loaded with the File API

 

 

Show:
© 2014 Microsoft