W3C

File API: Writer

W3C Working Draft 06 April 2010

This Version:
http://www.w3.org/TR/2010/WD-file-writer-api-20100406/
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
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] and [WEBWORKERS].

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 Device APIs and Policy Working Group as a First Public 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-device-apis@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.

2. 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] 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.

2.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.appendText("Lorem ipsum");
  writer.onwrite = done;
  writer.onerror = error;
  writer.write(bb.getBlob());
}

Here's an example of obtaining a FileWriter from a HTML input element:

var fileWriter = document.forms['downloadData']['fileChooser'].fileWriter;

3. The BlobBuilder interface

BlobBuilder description

Can we do without endings? Any choice other than "transparent" can be implemented by the app author, and most file formats don't care about line endings. "Transparent" 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?
[Constructor]
interface BlobBuilder {
    attribute DOMString endings;
    Blob getBlob ();
    void append (in DOMString text) raises (FileException);
    void append (in Blob data);
};

3.1 Attributes

endings of type DOMString

How strings containing \n are to be written out. Changing endings affects only subsequent calls to appendText, and has no effect on the current contents of the Blob. The possible values are:

ValueDescription
"transparent" Code points from the string remain untouched. This is the default value.
"native" Line-endings are handled according to the platform's preference.
"lf" A LF is used. This is used in Unix, Linux, and OSX systems.
"cr" A CR is used. This is the same as was used in antique Macintosh systems.
"crlf" A CRLF pair is used. This is the same as on Microsoft Windows systems.
No exceptions.

3.2 Methods

append

Appends the supplied text to the current contents of the BlobBuilder, writing it as UTF-8, taking into account the current state of endings.

ParameterTypeNullableOptionalDescription
textin DOMString The data to write.
ExceptionDescription
FileException
ENCODING_ERRThe value of endings does not correspond to a supported policy.
Return type: void
append

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

ParameterTypeNullableOptionalDescription
datain Blob The Blob to append.
No exceptions.
Return type: void
getBlob

Returns the current contents of the BlobBuilder as a Blob.

No parameters.
No exceptions.
Return type: Blob

3.3 Constructor

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

4. The FileWriter interface

This interface provides methods to write blobs to disk using progress events and event handler attributes [DOM3Events]. It is desirable to write data to file systems asynchronously in the main thread of user agents. This interface provides such an asynchronous API, and is specified to be used within the context of the global object (Window [HTML5]) as well as Web Workers (WorkerUtils [WEBWORKERS]).

[NoInterfaceObject]
interface FileWriter {
    void abort ();
    const unsigned short INIT = 0;
    const unsigned short WRITING = 1;
    const unsigned short DONE = 2;
    readonly attribute unsigned short readyState;
    readonly attribute FileError      error;
             attribute Function       onwritestart;
             attribute Function       onprogress;
             attribute Function       onwrite;
             attribute Function       onabort;
             attribute Function       onerror;
             attribute Function       onwriteend;
    readonly attribute long long      position;
    readonly attribute long long      length;
    void write (Blob data) raises (FileException);
    void seek (long long position) raises (FileException);
    void truncate (long long size) raises (FileException);
};

4.1 Attributes

error of type FileError, readonly

Description of error

No exceptions.
length of type 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.

No exceptions.
onabort of type Function

Handler for abort events.

No exceptions.
onerror of type Function

Handler for error events.

No exceptions.
onprogress of type Function

Handler for progress events.

No exceptions.
onwrite of type Function

Handler for write events.

No exceptions.
onwriteend of type Function

Handler for writeend events.

No exceptions.
onwritestart of type Function

Handler for writestart events.

No exceptions.
position of type long long, readonly

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

No exceptions.
readyState of type unsigned short, readonly

The FileWriter 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:

No exceptions.

4.2 Methods

abort

When the abort method is called, the user agent must run the steps below:TODO: refs<-->

  1. Set readyState to DONE and result to null.
  2. Terminate any steps while processing a write method.
  3. Dispatch a progress event called error. Set the error attribute to a FileError object with the appropriate code (in this case, ABORT_ERR; see error conditions).
  4. Dispatch a progress event called abort
  5. Dispatch a progress event called writeend
  6. Stop dispatching any further progress events.
No parameters.
No exceptions.
Return type: void
seek

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

Seek may not be called while the FileWriter is in the WRITING state.

ParameterTypeNullableOptionalDescription
positionlong long

An absolute byte offset into the file. If position is greater than length, length is used instead. If position 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.

ExceptionDescription
FileException
INVALID_STATE_ERRA user called write while readyState was WRITING.
Return type: void
truncate

Shortens the file to the length specified.

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

  1. If readyState is WRITING, throw a FileException with error code INVALID_STATE_ERR and terminate this overall series of steps.
  2. Set readyState to WRITING.
  3. If an error occurs during truncate, set readyState to DONE. Proceed to the error steps below.
    1. Dispatch a progress event called error. Set the error attribute; on getting the error attribute must be a FileError object with a valid error code that indicates the kind of file error that has occurred.
    2. Dispatch a progress event called writeend
    3. On getting, the length and position attributes should indicate any modification to the file.
    4. Terminate this overall set of steps.
  4. Queue a task to dispatch a progress event called writestart.
  5. When the file has been truncated, set readyState to DONE. Upon successful completion, position and length must be 0.
  6. Dispatch a progress event called write
  7. Dispatch a progress event called writeend
  8. Terminate this overall set of steps.
ParameterTypeNullableOptionalDescription
sizelong long The size to which the file is to be truncated, measured in bytes. If size is greater than or equal to length, this has no effect.
ExceptionDescription
FileException
INVALID_STATE_ERRA user called truncate while readyState was WRITING.
Return type: void
write

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

  1. If readyState is WRITING, throw a FileException with error code INVALID_STATE_ERR and terminate this overall series of steps.
  2. Set readyState to WRITING.
  3. If an error occurs during file write, set readyState to DONE. Proceed to the error steps below.
    1. Dispatch a progress event called error. Set the error attribute; on getting the error attribute must be a FileError object with a valid error code that indicates the kind of file error that has occurred.
    2. Dispatch a progress event called writeend
    3. On getting, the length and position attributes should indicate any fractional data successfully written to the file.
    4. Terminate this overall set of steps.
  4. Queue a task to dispatch a progress event called writestart.
  5. Make progress notifications. On getting, while processing the write method, the length and position attributes should indicate the progress made in writing the file as of the last progress notification.
  6. When the data has been fully written, set readyState to DONE. Upon successful completion, position and length must indicate an increase of data.size over their pre-write states, indicating the change to the underlying file.
  7. Dispatch a progress event called write
  8. Dispatch a progress event called writeend
  9. Terminate this overall set of steps.
ParameterTypeNullableOptionalDescription
dataBlob The blob to write.
ExceptionDescription
FileException
INVALID_STATE_ERRA user called write while readyState was WRITING.
Return type: void

4.3 Constants

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

4.4 The FileWriter Task Source

TODO: Figure out how to do the references properly. Maybe just use raw links to a reference section, as in the File API spec. <-->

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

5. The FileWriterSync interface

FileWriterSync description

[NoInterfaceObject]
interface FileWriterSync {
    readonly attribute long long position;
    readonly attribute long long length;
    void write (Blob data) raises (FileException);
    void seek (long long position) raises (FileException);
    void truncate (long long size) raises (FileException);
};

5.1 Attributes

length of type 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.

No exceptions.
position of type long long, readonly

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

No exceptions.

5.2 Methods

seek

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

ParameterTypeNullableOptionalDescription
positionlong long An absolute byte offset into the file. If position is greater than length, length is used instead. If position 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.
ExceptionDescription
FileException
TODOTODO
Return type: void
truncate

Shortens the file to the length specified.

ParameterTypeNullableOptionalDescription
sizelong long The size to which the file is truncated, measured in bytes. If size is greater than or equal to length, this has no effect.
ExceptionDescription
FileException
TODOTODO
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.
ExceptionDescription
FileException
TODOTODO
Return type: void

6. Errors and Exceptions

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

The directory containing the file being written may not exist at the time one of the asynchronous write methods or synchronous write methods 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 NOT_FOUND_ERR

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 NOT_FOUND_ERR

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 NO_MODIFICATION_ALLOWED_ERR

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 SECURITY_ERR

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

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

A web application may request unsupported line endings. See ENCODING_ERR

6.1 The FileError Interface

This interface extends the FileError interface described in [FILE-API] to add several new error codes. It is used to report errors asynchronously. The FileWriter object's error attribute is a FileError object, and is accessed asynchronously through the onerror event handler when error events are generated.

interface FileError {
    const unsigned short NO_MODIFICATION_ALLOWED_ERR = 7;
    const unsigned short NOT_FOUND_ERR = 8;
    const unsigned short INVALID_STATE_ERR = 11;
    const unsigned short SECURITY_ERR = 18;
    const unsigned short ABORT_ERR = 20;
    const unsigned short NOT_READABLE_ERR = 24;
    const unsigned short ENCODING_ERR = 26;
    readonly attribute unsigned short code;
};

6.1.1 Attributes

code of type unsigned short, readonly
No exceptions.

6.1.2 Constants

ABORT_ERR of type unsigned short
ENCODING_ERR of type unsigned short
INVALID_STATE_ERR of type unsigned short
NOT_FOUND_ERR of type unsigned short
NOT_READABLE_ERR of type unsigned short
NO_MODIFICATION_ALLOWED_ERR of type unsigned short
SECURITY_ERR of type unsigned short
The code attribute must return one of the constants of the FileError error, which must be the most appropriate code from the table below.

6.2 The FileException exception

This interface extends the FileException interface described in [FILE-API] to add several new error codes. Any errors that need to be reported synchronously, including all that occur during use of the synchronous write methods for Web Workers [WEBWORKERS] are reported using the FileException exception.
exception FileException {
    const unsigned short NO_MODIFICATION_ALLOWED_ERR = 7;
    const unsigned short NOT_FOUND_ERR = 8;
    const unsigned short INVALID_STATE_ERR = 11;
    const unsigned short SECURITY_ERR = 18;
    const unsigned short ABORT_ERR = 20;
    const unsigned short NOT_READABLE_ERR = 24;
    const unsigned short ENCODING_ERR = 26;
    readonly attribute unsigned short code;
};

6.2.1 Attributes

code of type unsigned short, readonly
No exceptions.

6.2.2 Constants

ABORT_ERR of type unsigned short
ENCODING_ERR of type unsigned short
INVALID_STATE_ERR of type unsigned short
NOT_FOUND_ERR of type unsigned short
NOT_READABLE_ERR of type unsigned short
NO_MODIFICATION_ALLOWED_ERR of type unsigned short
SECURITY_ERR of type unsigned short
The code attribute must return one of the constants of the FileException error, which must be the most appropriate code from the table below.

6.3 Error Code Descriptions

NameValueDescription
NO_MODIFICATION_ALLOWED_ERR7 User agents must use this code when attempting to write to a file which cannot be modified due to the state of the underlying filesystem.
NOT_FOUND_ERR8 User agents must use this code if:
  • 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.
INVALID_STATE_ERR11 User agents must use this code if an application attempts to initiate a write, truncate, or seek using a FileWriter which is already in the WRITING state.
SECURITY_ERR18 User agents may use this code if:
  • it is determined that certain files are unsafe for access within a Web application
  • it is determined that too many write calls are being made on file resources
  • it is determined that the file has changed on disk since the user selected it
This is a security error code to be used in situations not covered by any other error codes.
ABORT_ERR20 User agents must use this code if the read operation was aborted, typically with a call to abort().
ENCODING_ERR26 User agents must use this code when an application requests conversion of text using an unsupported line ending specifier.

7. Obtaining file writers

This spec describes one way to obtain a FileWriter. Not all user agents may implement this, and other methods may be provided by other specs.

The group has not at this time reached consensus on the best manner in which to obtain access to a file writer. Issues have been noted concerning the type=saveas approach, and it has been suggested that an API call to prompt for download directly would introduce no security risk not already present in the browser stack. Feedback from the community is particularly welcome on this point.

7.1 Obtaining file writers via HTML input element

A new HTML input element state is added with type=saveas, corresponding to the File SaveAs state. This functions similarly to the File Upload state, except that instead of presenting a File-Open picker and returning a list of File objects, it presents a File-Save-As picker and returns a single FileWriter. Here is a description of an input element in the File SaveAs state.

The input element represents write access to a selected file, embodied as a FileWriter.

If the element is mutable, the user agent should allow the user to change the selected file. The file can be an existing file in a filesystem [which is to be overwritten], or can be a new file.

If the element is required and the list of selected files is empty, then the element is suffering from being missing.

There must be no more than one file selected.

A FileWriter obtained from such an element must begin with position and length each set to 0, as no read access of any kind is granted by the user's selection of the file.

Bookkeeping details

  1. The following common input element content attribute applies to the element: required.
  2. The following common input element IDL attribute applies to the element: value.
  3. A new IDL attribute fileWriter applies, which holds a reference to a FileWriter object.
  4. The value IDL attribute is in mode filename, with the exception that there is only a single selected file, fileWriter, not a list, files. This means that setting value on an input element in the File SaveAs state will clear fileWriter rather than files.
  5. The change event applies.
  6. The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, multiple, pattern, placeholder, readonly, size, src, step, and width.
  7. The element's value attribute must be omitted.
  8. The following IDL attributes and methods do not apply to the element: checked, list, selectedOption, selectionStart, selectionEnd, valueAsDate, and valueAsNumber IDL attributes; select(), setSelectionRange(), stepDown(), and stepUp() methods.
  9. The input event does not apply.
This section needs more polishing than most to bring it up to snuff as an actual specification.
TODO: Explore integration with drag-out.

8. Security Considerations

This section is non-normative.

8.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 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.

8.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.

8.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.

8.4 Other Standard Techniques

Other parts of the download protection tool-chain such as flagging files as unsafe to open or refusing to create dangerous file names should 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

[FILE-API]
Arun Ranganathan. File API. 17 November 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-FileAPI-20091117/
[HTML5]
Ian Hickson; David Hyatt. HTML 5. 25 August 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-html5-20090825/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[WEBWORKERS]
Ian Hickson. Web Workers. 29 October 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-workers-20091029/

B.2 Informative references

No informative references.