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:
Blob
from a String.
Blob
to a file, and an event model to obtain the results
of those writes.Blob
to a file synchronously from the Worker
context.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.
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.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;
BlobBuilder
interfaceBlobBuilder description
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:
Value | Description |
---|---|
"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.
|
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, taking into account the
current state of endings
.
Appends the supplied Blob to the current contents of the
BlobBuilder
.
When the BlobBuilder constructor is invoked, the user agent must return a new BlobBuilder object.
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]]).
When the abort
method is called, the user agent MUST
run the steps below:TODO: refs<-->
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:
Description of error
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 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
.
When the write
method is called, the user agent 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
.readyState
to DONE
.
Proceed to the error steps below.
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.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.
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.
write
writeend
write
while readyState
was WRITING
.
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.
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.
write
while readyState
was WRITING
.
Shortens the file to the length specified.
When the truncate
method is called, the user agent 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
.readyState
to DONE
.
Proceed to the error steps below.
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.writeend
length
and
position
attributes SHOULD indicate any
modification to the file.writestart
.readyState
to DONE
. Upon successful
completion, position
and length
MUST
be 0.
write
writeend
size
is greater than or equal to
length
, this has no effect.
truncate
while
readyState
was WRITING
.
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.
FileWriterSync
interfaceFileWriterSync description
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.
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.
Shortens the file to the length specified.
size
is greater than or equal to length
,
this has no effect.
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
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.
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. |
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(). |
ENCODING_ERR | 26 | User agents MUST use this code when an application requests conversion of text using an unsupported line ending specifier. |
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.
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
required
.
value
.fileWriter
applies, which holds
a reference to a FileWriter object.
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
.accept
, alt
,
autocomplete
, checked
,
formaction
, formenctype
,
formmethod
, formnovalidate
,
formtarget
,
height
, list
, max
,
maxlength
, min
, multiple
,
pattern
, placeholder
,
readonly
, size
, src
,
step
, and width
.value
attribute must be omitted.checked
, list
,
selectedOption
, selectionStart
,
selectionEnd
, valueAsDate
, and
valueAsNumber
IDL attributes;
select()
, setSelectionRange()
,
stepDown()
, and stepUp()
methods.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.
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 or refusing to create dangerous file names 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.