Copyright © 2010 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
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:
BlobBuilder
interface, which enables one to build a
Blob
from a String.
FileSaver
interface, which provides methods to write a
Blob
to a file, and an event model to monitor the
progress of those writes.FileWriter
interface, which expands on FileSaver to add
a richer set of output options.FileWriterSync
interface, which provides methods to
write and modify files synchronously in a Web Worker.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.
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:
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.
The terms and algorithms event handler attributes, event handler event types, Function, task, task source, and queue a task are defined by the HTML 5 specification [HTML5].
The term Blob is defined by the File API specification [FILE-API].
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.
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.
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;
BlobBuilder
interfaceBlobBuilder description
[Constructor]
interface BlobBuilder {
Blob getBlob (optional in DOMString contentType);
void append (in DOMString text, optional in DOMString endings) raises (FileException
);
void append (in Blob data);
void append (in ArrayBuffer data);
};
append
Appends the supplied text to the current contents of the
BlobBuilder
, writing it as UTF-8, converting
newlines as
specified in endings
.
Parameter | Type | Nullable | Optional | Description | ||||||
---|---|---|---|---|---|---|---|---|---|---|
text | in DOMString | ✘ | ✘ | The data to write. | ||||||
endings | in DOMString | ✘ | ✔ |
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?
This parameter specifies how strings containing
|
Exception | Description | ||
---|---|---|---|
FileException |
|
void
append
Appends the supplied Blob
to the current contents of the
BlobBuilder
.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | in Blob | ✘ | ✘ | The data to append. |
void
append
Appends the supplied ArrayBuffer to the current contents of the
BlobBuilder
.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | in ArrayBuffer | ✘ | ✘ | The data to append. |
void
getBlob
Returns the current contents of the BlobBuilder
as a
Blob
.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
contentType | in
DOMString | ✘ | ✔ | Sets the content type of the blob produced. |
Blob
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.
FileSaver
interfaceThis interface provides methods to monitor the asynchronous writing of blobs to disk using progress events [PROGRESS-EVENTS] 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]).
[Constructor(in Blob data)]
interface FileSaver {
void abort () raises (FileException
);
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;
};
error
of
type FileError
, readonly
The last error that occurred on the FileSaver
.
onabort
of type FunctionHandler for abort events.
onerror
of type FunctionHandler for error events.
onprogress
of type FunctionHandler for progress events.
onwrite
of type FunctionHandler for write events.
onwriteend
of type FunctionHandler for writeend events.
onwritestart
of type FunctionHandler for writestart events.
readyState
of type unsigned short, readonlyThe 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:
abort
When the abort
method is called, user agents
must run the steps
below:TODO: refs<-->
readyState
is DONE
or
INIT
, throw a FileException
with
error
code INVALID_STATE_ERR
and terminate this
overall
series of steps.DONE
.Exception | Description | ||
---|---|---|---|
FileException |
|
void
DONE
of
type unsigned shortINIT
of type unsigned shortWRITING
of
type unsigned short
The FileSaver(data)
constructor takes one
argument: the
Blob of data to be saved to a file.
When the FileSaver
contructor 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.
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 contructor has returned, a new FileSaver must asynchronously execute the following steps.
readyState
to WRITING
.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.error
.DONE
.writeend
.writestart
.write
DONE
.writeend
The following are the event handler attributes (and
their
corresponding event handler event types)
that user agents must
support on
as DOM attributes:
FileSaver
event handler attribute | event handler event type |
---|---|
onwritestart |
writestart |
onprogress |
progress |
onwrite |
write |
onabort |
abort |
onerror |
error |
onwriteend |
writeend |
FileSaverSync
interfaceIt seems like this should have a blocking constructor and no methods or properties, if it's to follow the contructor-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.
FileWriter
interface
This interface expands on the FileSaver
interface to allow
for
multiple write actions, rather than just saving a single Blob.
[NoInterfaceObject]
interface FileWriter : FileSaver
{
readonly attribute unsigned long long position;
readonly attribute unsigned long long length;
void write (Blob data) raises (FileException
);
void seek (long long offset) raises (FileException
);
void truncate (unsigned long long size) raises (FileException
);
};
length
of type unsigned long long, readonlyThe 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.
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.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
offset | long long | ✘ | ✘ |
An absolute byte offset into the file. If |
Exception | Description | ||
---|---|---|---|
FileException |
|
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).
readyState
is WRITING
,
throw a
FileException
with error code
INVALID_STATE_ERR
and terminate this overall
series of
steps.readyState
to WRITING
.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.error
.DONE
.writeend
length
and
position
attributes should indicate any
modification to the file.writestart
.length
must
be equal to size
.position
must be the lesser of
size
.write
DONE
.writeend
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
size | unsigned long
long | ✘ | ✘ | The size to which the length of the file is to be adjusted, measured in bytes. |
Exception | Description | ||
---|---|---|---|
FileException |
|
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).
readyState
is WRITING
,
throw a
FileException
with error code
INVALID_STATE_ERR
and terminate this overall
series
of steps.readyState
to WRITING
.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.error
.DONE
.writeend
length
and
position
attributes should indicate any
fractional data successfully written to the file.writestart
.write
method, the length
and
position
attributes should indicate the progress
made in writing the file as of the last progress
notification.
position
and length
must
indicate an increase of data.size
over
their
pre-write states, indicating the change to the
underlying
file.write
DONE
.writeend
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | Blob | ✘ | ✘ | The blob to write. |
Exception | Description | ||
---|---|---|---|
FileException |
|
void
FileWriterSync
interfaceThis 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]).
[NoInterfaceObject]
interface FileWriterSync {
readonly attribute unsigned long long position;
readonly attribute unsigned long long length;
void write (Blob data) raises (FileException
);
void seek (long long offset) raises (FileException
);
void truncate (unsigned long long size) raises (FileException
);
};
length
of type unsigned long long, readonlyThe 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
.
seek
Seek sets the file position at which the next write will occur.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
offset | long 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.
|
Exception | Description | ||
---|---|---|---|
FileException |
|
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
size
.Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
size | unsigned long
long | ✘ | ✘ | The size to which the length of the file is to be adjusted, measured in bytes. |
Exception | Description | ||||||
---|---|---|---|---|---|---|---|
FileException |
|
void
write
Write the supplied data to the file at position
.
Upon completion, position
will increase by
data.size
.
Parameter | Type | Nullable | Optional | Description |
---|---|---|---|---|
data | Blob | ✘ | ✘ | The blob to write. |
Exception | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
FileException |
|
void
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 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 SYNTAX_ERR.
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 NOT_FOUND_ERR = 1;
const unsigned short SECURITY_ERR = 2;
const unsigned short ABORT_ERR = 3;
const unsigned short NOT_READABLE_ERR = 4;
const unsigned short ENCODING_ERR = 5;
const unsigned short NO_MODIFICATION_ALLOWED_ERR = 6;
const unsigned short INVALID_STATE_ERR = 7;
const unsigned short SYNTAX_ERR = 8;
readonly attribute unsigned short code;
};
code
of type unsigned short, readonlyABORT_ERR
of type unsigned shortENCODING_ERR
of
type unsigned shortINVALID_STATE_ERR
of
type unsigned shortNOT_FOUND_ERR
of type unsigned shortNOT_READABLE_ERR
of
type unsigned shortNO_MODIFICATION_ALLOWED_ERR
of type unsigned shortSECURITY_ERR
of
type unsigned shortSYNTAX_ERR
of type unsigned shortFileError
error, which must be the most
appropriate code from the
Error
Code Descriptions.
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 NOT_FOUND_ERR = 1;
const unsigned short SECURITY_ERR = 2;
const unsigned short ABORT_ERR = 3;
const unsigned short NOT_READABLE_ERR = 4;
const unsigned short ENCODING_ERR = 5;
const unsigned short NO_MODIFICATION_ALLOWED_ERR = 6;
const unsigned short INVALID_STATE_ERR = 7;
const unsigned short SYNTAX_ERR = 8;
unsigned short code;
};
code
of
type unsigned shortABORT_ERR
of type unsigned shortENCODING_ERR
of type unsigned shortINVALID_STATE_ERR
of type unsigned shortNOT_FOUND_ERR
of type unsigned shortNOT_READABLE_ERR
of type unsigned shortNO_MODIFICATION_ALLOWED_ERR
of type unsigned shortSECURITY_ERR
of type unsigned shortSYNTAX_ERR
of
type unsigned shortFileException
error, which must be the most
appropriate code from
the Error
Code Descriptions.
Name | Value | Description |
---|---|---|
NO_MODIFICATION_ALLOWED_ERR | 7 | 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_ERR | 8 | User agents must
use this code if:
|
INVALID_STATE_ERR | 11 | 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.
|
SYNTAX_ERR | 12 | User agents must use this code when an application attempts to supply an invalid line ending specifier to the API. |
SECURITY_ERR | 18 |
User agents may
use this code if:
|
ABORT_ERR | 20 | User agents must use this code if the read operation was aborted, typically with a call to abort(). |
This section is non-normative.
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.
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.
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.
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 should naturally be applied.
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.
No informative references.