W3C

File API: Writer

W3C Working Draft 17 April 2012

This version:
http://www.w3.org/TR/2012/WD-file-writer-api-20120417/
Latest published version:
http://www.w3.org/TR/file-writer-api/
Latest editor's draft:
http://dev.w3.org/2009/dap/file-system/file-writer.html
Previous version:
http://www.w3.org/TR/2011/WD-file-writer-api-20110419/
Editor:
Eric Uhrhane, Google

Abstract

This specification defines an API for writing to files from web applications. This API is designed to be used in conjunction with, and depends on definitions in, other APIs and elements on the web platform. Most relevant among these are [FILE-API-ED] and [WEBWORKERS-ED].

This API includes:

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document represents the early consensus of the group on the scope and features of the proposed File API: Writer. Issues and editors notes in the document highlight some of the points on which the group is still working and would particularly like to get feedback.

This document was published by the WebApps Working Group as a Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-webapps@w3.org (subscribe, archives). All feedback is welcome.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words must, must not, required, should, should not, recommended, may, and optional in this specification are to be interpreted as described in [RFC2119].

This specification defines conformance criteria that apply to a single product: user agents that implement the interfaces that it contains.

Everything in this specification is normative except for examples and sections marked as being informative.

The keywords must, must not, required, shall, shall not, should, should not, recommended, may, and optional in this document are to be interpreted as described in Key words for use in RFCs to Indicate Requirement Levels [RFC2119].

The following conformance classes are defined by this specification:

conforming implementation

A user agent is considered to be a conforming implementation if it satisfies all of the must-, required- and shall-level criteria in this specification that apply to implementations.

2. Terminology and Algorithms

The terms and algorithms event handler attributes, event handler event types, Function, task, task queue, task source, and queue a task are defined by the HTML 5 specification [HTML5].

When this specification refers to a write method, it includes both write and truncate.

When this specification refers to a write algorithm, it includes the algorithm invoked by any write method as well as the FileSaver write algorithm.

When this specification says to terminate an algorithm the user agent must terminate the algorithm after finishing the step it is on. Any write algorithm defined in this specification can be terminated by an abort() call.

When this specification says to make progress notifications, the following are normative:

When this specification says to fire a progress event called e (for some ProgressEvent e), the following are normative:

The term throw in this specification, as it pertains to exceptions, is used as defined in the DOM4 specification [DOM4].

The term Blob is defined by the File API specification [FILE-API-ED].

The term ArrayBuffer is defined by the Typed Arrays specification [TYPED-ARRAYS].

This specification includes algorithms (steps) as part of the definition of methods. Conforming implementations (referred to as user agents from here on) may use other algorithms in the implementation of these methods, provided the end result is the same.

3. Introduction

This section is non-normative.

Web applications are currently fairly limited in how they can write to files. One can present a link for download, but creating and writing files of arbitrary type, or modifying downloaded files on their way to the disk, is difficult or impossible. This specification defines an API through which user agents can permit applications to write generated or downloaded files.

The [FILE-API-ED] defined interfaces for reading files, manipulation of Blobs of data, and errors raised by file accesses. This specification extends that work with a way to construct Blobs and with synchronous and asynchronous file-writing interfaces. As with reading, writing files on the main thread should happen asynchronously to avoid blocking UI actions. Long-running writes provide status information through delivery of progress events.

3.1 Examples

Here is a simple function that writes a text file, given a FileWriter:

function writeFile(writer) {
  function done(evt) {
    alert("Write completed.");
  }
  function error(evt) {
    alert("Write failed:" + evt);
  }

  var bb = new BlobBuilder();
  bb.append("Lorem ipsum");
  writer.onwrite = done;
  writer.onerror = error;
  writer.write(bb.getBlob());
}

Here's an example of obtaining and using a FileSaver:

var bb = new BlobBuilder();
bb.append("Lorem ipsum");
var fileSaver = window.saveAs(bb.getBlob(), "test_file");
fileSaver.onwriteend = myOnWriteEnd;

4. The BlobBuilder interface

The BlobBuilder is used to construct Blobs.

The BlobBuilder interface is deprecated in favor of the new constructible Blob. However, at this time implementations generally support BlobBuilder and not constructible Blob.
[Constructor]
interface BlobBuilder {
    Blob getBlob (optional DOMString contentType);
    void append (DOMString text, optional DOMString endings);
    void append (Blob data);
    void append (ArrayBuffer data);
};

4.1 Methods

append

Appends the supplied text to the current contents of the BlobBuilder, writing it as UTF-8, converting newlines as specified in endings.

ParameterTypeNullableOptionalDescription
textDOMString The data to write.
endingsDOMString
Can we do without endings? Any choice other than "native" can be implemented by the app author, and most file formats don't care about line endings. "Native" would be handy for sharing certain types of text files with apps outside the browser [e.g. Makefiles on a system where make is expecting \n will have issues if they're written with \r\n]. Is it worth it? Can this be worked around if we don't supply it?

This parameter specifies how strings containing \n are to be written out. If the user does not provide the endings parameter, user agents must act as if the user had specified a value of 'transparent'. If the user provides the endings parameter, user agents must convert newlines as specified below. The possible values are:

ValueDescription
"transparent" Code points from the string must remain unchanged.
"native" Newlines must be transformed to the default line-ending representation of the underlying host operating system. For example, if the underlying OS is Windows, newlines will be transformed into \r\n pairs as the text is appended to the state of the BlobBuilder.
Return type: void
append

Appends the supplied Blob to the current contents of the BlobBuilder.

ParameterTypeNullableOptionalDescription
dataBlob The data to append.
Return type: void
append

Appends the supplied ArrayBuffer to the current contents of the BlobBuilder.

ParameterTypeNullableOptionalDescription
dataArrayBuffer The data to append.
Return type: void
getBlob

Returns the current contents of the BlobBuilder as a Blob.

ParameterTypeNullableOptionalDescription
contentTypeDOMString Sets the content type of the blob produced.
Return type: Blob

4.2 Constructor

When the BlobBuilder constructor is invoked, user agents must return a new BlobBuilder object.

This constructor must be visible when the script's global object is either a Window object or an object implementing the WorkerUtils interface.

5. The FileSaver interface

This interface provides methods to monitor the asynchronous writing of blobs to disk using progress events [PROGRESS-EVENTS-ED] and event handler attributes.

This interface is specified to be used within the context of the global object (Window [HTML5]) and within Web Workers (WorkerUtils [WEBWORKERS-ED]).

[Constructor(Blob data)]
interface FileSaver : EventTarget {
    void abort ();
    const unsigned short INIT = 0;
    const unsigned short WRITING = 1;
    const unsigned short DONE = 2;
    readonly attribute unsigned short readyState;
    readonly attribute DOMError       error;
    [TreatNonCallableAsNull]
             attribute Function       onwritestart;
    [TreatNonCallableAsNull]
             attribute Function       onprogress;
    [TreatNonCallableAsNull]
             attribute Function       onwrite;
    [TreatNonCallableAsNull]
             attribute Function       onabort;
    [TreatNonCallableAsNull]
             attribute Function       onerror;
    [TreatNonCallableAsNull]
             attribute Function       onwriteend;
};

5.1 Attributes

error of type DOMError, readonly

The last error that occurred on the FileSaver.

onabort of type Function

Handler for abort events.

onerror of type Function

Handler for error events.

onprogress of type Function

Handler for progress events.

onwrite of type Function

Handler for write events.

onwriteend of type Function

Handler for writeend events.

onwritestart of type Function

Handler for writestart events.

readyState of type unsigned short, readonly

The FileSaver object can be in one of 3 states. The readyState attribute, on getting, must return the current state, which must be one of the following values:

5.2 Methods

abort

When the abort method is called, user agents must run the steps below:

  1. If readyState == DONE or readyState == INIT, terminate this overall series of steps without doing anything else.
  2. Set readyState to DONE.
  3. If there are any tasks from the object's FileSaver task source in one of the task queues, then remove those tasks.
  4. Terminate the write algorithm being processed.
  5. Set the error attribute to a DOMError object of type "AbortError".
  6. Fire a progress event called abort
  7. Fire a progress event called writeend
  8. Terminate this algorithm.

No parameters.
Return type: void

5.3 Constants

DONE of type unsigned short
The entire Blob has been written to the file, an error occurred during the write, or the write was aborted using abort(). The FileSaver is no longer writing the blob.
INIT of type unsigned short
The object has been constructed, but there is no pending write.
WRITING of type unsigned short
The blob is being written.

5.4 The FileSaver Constructor

The FileSaver(data) constructor takes one argument: the Blob of data to be saved to a file.

When the FileSaver constructor is called, the user agent must return a new FileSaver object with readyState set to INIT.

This constructor must be visible when the script's global object is either a Window object or an object implementing the WorkerUtils interface.

5.5 The FileSaver Task Source

The FileSaver interface enables asynchronous writes on individual files by dispatching events to event handler methods. Unless stated otherwise, the task source that is used in this specification is the FileSaver. This task source is used for any event task that is asynchronously dispatched, or for event tasks that are queued for dispatching.

After its constructor has returned, a new FileSaver must asynchronously execute the following steps. They are referred to elsewhere as the FileSaver write algorithm.

  1. Set readyState to WRITING.
    FileSaver should really set readyState to WRITING before the user gets a handle to it, so that abort works. But FileWriter shouldn't, so it can't be an enforced part of the inherited interface. Also, writestart should be tied to the INIT->WRITING transition, so how would the holder of a FileSaver that wasn't a FileWriter ever see that?
  2. If an error occurs during file write, proceed to the error steps below.
    1. Queue a task that will:
      1. Set the error attribute; on getting the error attribute must be a DOMError object whose type indicates the kind of error that has occurred.
      2. Set readyState to DONE.
      3. Fire a progress event called error.
      4. Fire a progress event called writeend.
    2. Terminate this overall set of steps.
  3. Queue a task to fire a progress event called writestart.
  4. Make progress notifications.
  5. On completion of the write, queue a task to:
    1. Set readyState to DONE.
    2. Fire a progress event called write.
    3. Fire a progress event called writeend.
    4. Terminate this overall set of steps.

5.6 Event Handler Attributes

The following are the event handler attributes (and their corresponding event handler event types) that user agents must support on FileSaver as DOM attributes:

event handler attribute event handler event type
onwritestart writestart
onprogress progress
onwrite write
onabort abort
onerror error
onwriteend writeend

6. The FileSaverSync interface

It seems like this should have a blocking constructor and no methods or properties, if it's to follow the constructor-based model of the asynchronous interface. A global method seems like it would be cleaner, though. Is it important that they match? If so, the asynch constructor could turn into a method instead.

It's been pointed out that a method name like "saveAs" is too short and generic; any global symbol should be longer and more explicit in order to avoid confusion and naming conflicts.

7. The FileWriter interface

This interface expands on the FileSaver interface to allow for multiple write actions, rather than just saving a single Blob.

Since this is intended to be used only with the sandboxed filesystem, it could potentially move to the filesystem spec.
interface FileWriter : FileSaver {
    readonly attribute unsigned long long position;
    readonly attribute unsigned long long length;
    void write (Blob data);
    void seek (long long offset);
    void truncate (unsigned long long size);
};

7.1 Attributes

length of type unsigned long long, readonly

The length of the file. If the user does not have read access to the file, this must be the highest byte offset at which the user has written.

position of type unsigned long long, readonly

The byte offset at which the next write to the file will occur. This must be no greater than length.
A newly-created FileWriter must have position set to 0.

7.2 Methods

seek

Seek sets the file position at which the next write will occur.

When the seek method is called, user agents must run the steps below.

  1. If readyState is WRITING, throw an InvalidStateError and terminate this series of steps.
  2. Set position to offset.
  3. If position > length then set position to length.
  4. If position < 0 then set position to position + length.
  5. If position < 0 then set position to 0.

ParameterTypeNullableOptionalDescription
offsetlong long

If nonnegative, an absolute byte offset into the file.
If negative, an offset back from the end of the file.

Return type: void
truncate

Changes the length of the file to that specified. If shortening the file, data beyond the new length must be discarded. If extending the file, the existing data must be zero-padded up to the new length.

When the truncate method is called, user agents must run the steps below (unless otherwise indicated).

  1. If readyState is WRITING, throw an InvalidStateError and terminate this series of steps.
  2. Set readyState to WRITING.
  3. If an error occurs during truncate, proceed to the error steps below.
    1. Set the error attribute; on getting the error attribute must be a DOMError object whose type indicates the kind of error that has occurred.
    2. Set readyState to DONE.
    3. Fire a progress event called error.
    4. Fire a progress event called writeend
    5. On getting, the length and position attributes should indicate any modification to the file.
    6. Terminate this overall set of steps.
  4. Fire a progress event called writestart.
  5. Return from the truncate method, but continue processing the other steps in this algorithm.
  6. Upon successful completion:
    • length must be equal to size.
    • position must be the lesser of
      • its pre-truncate value,
      • size.
    • Queue a task to:
      1. Set readyState to DONE.
      2. Fire a progress event called write
      3. Fire a progress event called writeend
      4. Terminate this overall set of steps.

ParameterTypeNullableOptionalDescription
sizeunsigned long long The size to which the length of the file is to be adjusted, measured in bytes.
Return type: void
write

Write the supplied data to the file at position. When the write method is called, user agents must run the steps below (unless otherwise indicated).

  1. If readyState is WRITING, throw an InvalidStateError and terminate this series of steps.
  2. Set readyState to WRITING.
  3. If an error occurs during file write, proceed to the error steps below.
    1. Set the error attribute; on getting the error attribute must be a DOMError object whose type indicates the kind of error that has occurred.
    2. Set readyState to DONE.
    3. Fire a progress event called error.
    4. Fire a progress event called writeend
    5. On getting, the length and position attributes should indicate any fractional data successfully written to the file.
    6. Terminate this overall set of steps.
  4. Fire a progress event called writestart.
  5. Return from the write method, but continue processing the other steps in this algorithm.
  6. Make progress notifications. On getting, while processing the write method, the length and position attributes must indicate the progress made in writing the file as of the last progress notification.
  7. Upon successful completion of a write:
    • position must indicate an increase of data.size over its pre-write state.
    • length must be the greater of (the pre-write length) and (the pre-write position plus data.size).
    • Queue a task to:
      1. Set readyState to DONE.
      2. Fire a progress event called write.
      3. Fire a progress event called writeend.
      4. Terminate this overall set of steps.

ParameterTypeNullableOptionalDescription
dataBlob The blob to write.
Return type: void

8. The FileWriterSync interface

This interface lets users write, truncate, and append to files using simple synchronous calls.

This interface is specified to be used only within Web Workers (WorkerUtils [WEBWORKERS-ED]).

Since this is intended to be used only with the sandboxed filesystem, it could potentially move to the filesystem spec.
interface FileWriterSync {
    readonly attribute unsigned long long position;
    readonly attribute unsigned long long length;
    void write (Blob data);
    void seek (long long offset);
    void truncate (unsigned long long size);
};

8.1 Attributes

length of type unsigned long long, readonly

The length of the file. If the user does not have read access to the file, this must be the highest byte offset at which the user has written.

position of type unsigned long long, readonly

The byte offset at which the next write to the file will occur. This must be no greater than length.

8.2 Methods

seek

Seek sets the file position at which the next write will occur.

ParameterTypeNullableOptionalDescription
offsetlong long An absolute byte offset into the file. If offset is greater than length, length is used instead. If offset is less than zero, length is added to it, so that it is treated as an offset back from the end of the file. If it is still less than zero, zero is used.
Return type: void
truncate

Changes the length of the file to that specified. If shortening the file, data beyond the new length must be discarded. If extending the file, the existing data must be zero-padded up to the new length.

Upon successful completion:

  • length must be equal to size.
  • position must be the lesser of
    • its pre-truncate value,
    • size.

ParameterTypeNullableOptionalDescription
sizeunsigned long long The size to which the length of the file is to be adjusted, measured in bytes.
Return type: void
write

Write the supplied data to the file at position. Upon completion, position will increase by data.size.

ParameterTypeNullableOptionalDescription
dataBlob The blob to write.
Return type: void

9. Errors and Exceptions

9.1 Occurrence

This section is non-normative.

Error conditions can occur when attempting to write files. The list below of potential error conditions is informative, with links to normative descriptions of errors:

The directory containing the file being written may not exist at the time an asynchronous or synchronous write method is called. This may be due to it having been moved or deleted after a reference to it was acquired (e.g. concurrent modification with another application).
See NotFoundError.

The file being written may have been removed. If the file is not there, writing to an offset other than zero is not permitted.
See NotFoundError.

A file may be unwritable. This may be due to permission problems that occur after a reference to a file has been acquired (e.g. concurrent lock with another application).
See NoModificationAllowedError.

User agents may determine that some files are unsafe for use within web applications. Additionally, some file and directory structures may be considered restricted by the underlying filesystem; attempts to write to them may be considered a security violation. See the security considerations.
See SecurityError.

A web application may attempt to initiate a write, seek, or truncate via a FileWriter in the WRITING state.
See InvalidStateError.

During the writing of a file, the web application may itself wish to abort the call to an asynchronous write method.
See AbortError.

A web application may request unsupported line endings. See SyntaxError.

As documented in [FILE-API-ED], various errors may occur during reading from the Blob that is the source of the data to be written. These include NotFoundError, SecurityError, and NotReadableError.

9.2 Definitions

Synchronous write methods must throw an exception of the most appropriate type in the table below if there has been an error with writing.

If an error occurs while processing an asynchronous write method, the error attribute of the FileSaver object must return a DOMError object [DOM4] of the most appropriate type from the table below. Otherwise it must return null.

Error Descriptions

NameDescription
AbortError The read operation was aborted, typically with a call to abort().
InvalidStateError An application attempted to initiate a write, truncate, or seek using a FileWriter which is already in the WRITING state.
NotFoundError One or more of the following occurred:
  • the directory containing the file to be written could not be found at the time the write was processed.
  • the file to be written does not exist at the time the write was processed, and an offset other than zero is specified.
  • the blob that is the source of data to be written could not be found at the time the write was processed.
NoModificationAllowedError The application attempted to write to a file which cannot be modified due to the state of the underlying filesystem.
NotReadableError The source Blob could not be read, typically due to permission problems that occur after the Blob reference was acquired.
QuotaExceededError The operation failed because it would have caused the application to exceed its storage quota.
SecurityError One or more of the following occurred:
  • it was determined that certain files are unsafe for access within a Web application
  • it was determined that too many write calls are being made on file resources
  • it was determined that the file to be written, or the source data to be read, has changed on disk since the user selected it
This is an error to be used in situations not covered by any other error.
SyntaxError The application attempted to supply an invalid line ending specifier to the API.

10. Security Considerations

This section is non-normative.

10.1 Basic Security Model

Most of the security issues pertaining to writing to a file on the user's drive are the same as those involved in downloading arbitrary files from the Internet. The primary difference [in the case of FileWriter] stems from the fact that the file may be continuously written and re-written, at least until such a time as it is deemed closed by the user agent. This has an impact on disk quota, IO bandwidth, and on processes that may require analysing the content of the file.

10.2 Write-Only Files

When a user grants an application write access to a file, it doesn't necessarily imply that the app should also receive read access to that file or any of that file's metadata [including length]. This specification describes a way in which that information can be kept secret for write-only files. If the application has obtained a FileWriter through a mechanism that also implies read access, those restrictions may be relaxed.

10.3 Quotas

Where quotas are concerned, user agents may wish to monitor the size of the file(s) being written and possibly interrupt the script and warn the user if certain limits of file size, remaining space, or disk bandwidth are reached.

10.4 Other Standard Techniques

Other parts of the download protection tool-chain such as flagging files as unsafe to open, refusing to create dangerous file names, and making sure that the mime type of a file matches its extension may naturally be applied.

A. Acknowledgements

Thanks to Arun Ranganathan for his File API, Opera for theirs, and Robin Berjon both for his work on various file APIs and for ReSpec.

B. References

B.1 Normative references

[DOM4]
Anne van Kesteren; Aryeh Gregor; Ms2ger. DOM4. 5 January 2012. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2012/WD-dom-20120105/
[FILE-API-ED]
Arun Ranganathan; Jonas Sicking. File API. W3C Editor's Draft. (Work in progress.) URL: http://dev.w3.org/2006/webapi/FileAPI/
[HTML5]
Ian Hickson. HTML5. 29 March 2012. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/html5
[PROGRESS-EVENTS-ED]
Anne van Kesteren. Progress Events 1.0. W3C Editor's Draft. (Work in progress.) URL: http://dvcs.w3.org/hg/progress/raw-file/tip/Overview.html
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[TYPED-ARRAYS]
David Herman, Kenneth Russell. Typed Arrays Khronos Working Draft. (Work in progress.) URL: https://www.khronos.org/registry/typedarray/specs/latest/
[WEBWORKERS-ED]
Ian Hickson. Web Workers. W3C Editor's Draft. (Work in progress.) URL: http://dev.w3.org/html5/workers/

B.2 Informative references

No informative references.