FileHandle API

This article is in need of a technical review.

This article is in need of an editorial review.

The FileHandle API allows to manipulate files, including creating files and modifying their content (unlike the File API). The editing part uses a turn-based locking mechanism in order to avoid race issues.

API

Create a FileHandle

In order to create a FileHandle instance, one needs an IndexedBD Database.

var idbreq = indexedDB.open("MyTestDatabase");

idbreq.onsuccess = function(){
  var db = idbreq.result;
  var handleReq = db.mozCreateFileHandle("test.bin", "binary");
    
  handleReq.onsuccess = function(){
    var handle = handleReq.result;
    console.log('handle', handle);
  };
};

mozCreateFileHandle() takes two arguments: a name and an optional type. Both of these, however, are just descriptive and are not used by the database. The name can be an empty string, for example, and it doesn't even have to be unique. The API doesn't care about the values of these parameters.

Note that above code only creates a "temporary file" that exists only while you hold the FileHandle instance. If you want a file to survive a page refresh/app relaunch, you need to store the handle in a more permament location, like the the database itself.

var transaction = /old?u=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWebAPI%2Fdb.transaction%28%5B&y=1999"test"], "readwrite");
var objectStore = transaction.objectStore("test");
objectStore.add(myFile, myKey).onsuccess = function(event) {
  // The file is now referenced from database too.
}

FileHandle interface

interface FileHandle
{
  LockedFile open(optional DOMString mode);
  DOMRequest getFile()
  readonly attribute DOMString name;
  readonly attribute DOMString type;
  attribute Function? onabort;
  attribute Function? onerror;
};
open([mode="readonly"])
Returns a LockedFile. mode can be "readonly" or "readwrite"
getFile()
Returns a DOMRequest for a File. Upon success, you receive a read-only "snapshot" of file's content in the form of a File instance (that can be used anywhere a Blob is accepted, like FileReader, XHR, etc).
myFile.getFile().onsuccess = function(event) {
  var file = event.target.result;
  var transcation = myDatabase.transaction(["snapshots"], "readwrite");
  var objectStore = transaction.objectStore("snapshots");
  objectStore.add(file, snapshotKey).onsuccess = function(event) {
    // A new readonly copy of the file has been created.
  }
}
name
File name
type
Refers to the content-type
abort event
Happens when the locked file has been aborted
error event
Happens when there is any sort of internal error

LockedFile interface

interface LockedFile
{
  readonly attribute FileHandle fileHandle;
  readonly attribute DOMString mode;
  readonly attribute boolean active;
  attribute any? location;
  FileRequest getMetadata(optional FileMetadataParameters parameters);
  FileRequest readAsArrayBuffer(unsigned long long size);
  FileRequest readAsText(unsigned long long size, optional DOMString encoding);
  FileRequest write(DOMString or ArrayBuffer or Blob value);
  FileRequest append(DOMString or ArrayBuffer or Blob value);
  FileRequest truncate(optional unsigned long long size);
  FileRequest flush();
  void abort();
  attribute Function? oncomplete;
  attribute Function? onabort;
  attribute Function? onerror;
};
fileHandle
FileHandle instance from which the lock was open
mode
"readonly" or "readwrite"
active
When created, the LockedFile is active. This LockedFile is the only object with write access to the actual underlying file. Operations on a LockedFile are performed in isolation, meaning that once a LockedFile is active, all operations of this LockedFile are guaranteed to happen sequentially on the underlying file without being interleaved with operations from other LockedFiles.
When the LockedFile becomes inactive, trying to perform read/write operations on the via using the same LockedFile will throw an error.
location
Offset in the file. This value is changed automatically after every read and every write. Reads and writes occur starting at the location. null means end-of-file
getMetadata(parameters)
Returns a FileRequest for metadata. The argument is an object with parameter names as object keys and booleans as value to retrieve the given properties asynchronously. No value means true. Currently, the possible parameters are size and lastModified.
readAsArrayBuffer(size)
Returns a FileRequest for an ArrayBuffer of the given size. The operation starts at the location. Moves location by the number of read bytes.
readAsText(size [, encoding])
Returns a FileRequest for a string of the given size with the provided encoding. The operation starts at the location. Moves location by the number of read bytes. Works the same way as the equivalent method in the FileReader API.
var lockedFile = myFile.open();
var request = lockedFile.readAsText(3);
request.onsuccess = function(event) {
  var text = request.result;
  // 3 characters have been read.
}
write(value)
Returns a FileRequest for the success or failure of the write operation. The write starts at the location and moves the location by the number of written bytes.
var lockedFile = myFile.open("readwrite");
var request = lockedFile.write("foo");
request.onsuccess = function(event) {
  // The string "foo" has been written.
}
append(value)
Returns a FileRequest for the success or failure of the append operation. The value is appended at the end of the file, regardless of the location. After the data is appended, location is set to null.
truncate([size])
Returns a FileRequest for the success or failure of the truncate operation.
If the method is called with a single argument, after a successful truncate, what remains on the file are the first size bytes regardless of the location.
If the method is called with no argument, what remains is the location first bytes.
flush()
This forces the buffered data to be transfered to disk. After a success notified by the returned FileRequest, you can be guaranteed that if the application crashes or is inadvertedly interrupted, the data is on disk.
abort()
Makes the LockedFile inactive and cancels all not already perfomed operations.
complete, abort, error events

FileRequest interface

An object of this type is returned by all asynchronous operations of the LockedFile interface. It inherits from DOMRequest and is similar to IDBRequest, with the addition of the onprogress event. Upon success, the, the result of the requested file operation is accessible from the result property.

interface FileRequest : DOMRequest
{
  readonly attribute LockedFile lockedFile;
  attribute Function? onprogress;
};

Description

Why a different API than FileWriter?

The FileWriter specification defines FileWriters, objects aiming at representing editable files. Discussions on public-webapps led to the conclusion that the API would poorly behave in the case of different entities writing concurrently on the same file. The outcome of this discussion is the FileHandle API with its LockedFile and transaction mechanim.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support Not supported 15 Not supported Not supported Not supported
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support Not supported 15 Not supported Not supported Not supported

Tags (1)

Contributors to this page: tomica, ethertank, dbruant
Last updated by: ethertank,
Last reviewed by: ethertank,