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:
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 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 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:
progress
at the
FileSaver object about every 50ms or for every byte written,
whichever is less frequent.progress
MUST fire before write
is fired, and at 100% completion
of the write operation; if 100% of the file can written in less than
50ms, user agents MUST fire a progress event called
progress
at completion.
When this specification says to fire a progress event called
e
(for some ProgressEvent
e
), the
following are normative:
e
does not bubble.
e.bubbles
MUST be false [[!DOM4]].e
is NOT cancelable.
e.cancelable
MUST be false [[!DOM4]].
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.
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
interfaceThe BlobBuilder is used to construct Blobs.
Returns the current contents of the BlobBuilder
as a
Blob.
Appends the supplied text to the current contents of the
BlobBuilder
, writing it as UTF-8, converting newlines as
specified in endings
.
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:
Value | Description |
---|---|
"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.
|
Appends the supplied Blob to the current contents of the
BlobBuilder
.
Appends the supplied ArrayBuffer to the current contents of the
BlobBuilder
.
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.
This 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]]).
When the abort
method is called, user agents
MUST run the steps below:
readyState == DONE
or
readyState == INIT
, terminate this
overall series of steps without doing anything else.readyState
to DONE
.error
attribute to a
DOMError
object of type "AbortError".abort
writeend
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:
The last error that occurred on the FileSaver
.
Handler for writestart events.
Handler for progress events.
Handler for write events.
Handler for abort events.
Handler for error events.
Handler for writeend events.
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.
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.
readyState
to WRITING
.error
attribute; on getting the
error
attribute MUST be a
DOMError
object whose type
indicates the kind of error that has occurred.DONE
.error
.writeend
.writestart
.DONE
.write
.writeend
.
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 |
FileSaverSync
interfaceIt 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.
This interface expands on the FileSaver interface to allow for multiple write actions, rather than just saving a single Blob.
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.
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.
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 an InvalidStateError and terminate this series
of steps.readyState
to WRITING
.error
attribute; on getting the
error
attribute MUST be a
DOMError
object whose type
indicates the kind of error that has occurred.DONE
.error
.writeend
length
and
position
attributes SHOULD indicate any
fractional data successfully written to the file.writestart
.write
method, the
length
and position
attributes MUST
indicate the progress made in writing the file as of the last
progress notification.
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
).DONE
.write
.writeend
.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.
readyState
is WRITING
,
throw an InvalidStateError and terminate this series
of steps.position
to offset
.position > length
then set
position
to length.position < 0
then set
position
to position + length
.position < 0
then set
position
to 0
.
If nonnegative, an absolute byte offset into the file.
If negative, an offset back from the end of the file.
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
an InvalidStateError and terminate this series of steps.readyState
to WRITING
.error
attribute; on getting the
error
attribute MUST be a
DOMError
object whose type
indicates the kind of error that has occurred.DONE
.error
.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
.DONE
.write
writeend
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]]).
The byte offset at which the next write to the file will occur.
This MUST be no greater than length
.
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.
Write the supplied data to the file at position
.
Upon completion, position
will increase by
data.size
.
Seek sets the file position at which the next write will occur.
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.
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
.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]], 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.
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
.
Name | Description |
---|---|
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:
|
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:
|
SyntaxError | The application attempted to supply an invalid line ending specifier to the API. |
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 may 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.