GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing w3c.github.io — File API 1. IntroductionThis section is informative. Web applications should have the ability to manipulate as wide as possible a range of user input, including files that a user may wish to upload to a remote server or manipulate inside a rich web application. This specification defines the basic representations for files, lists of files, errors raised by access to files, and programmatic ways to read files. Additionally, this specification also defines an interface that represents "raw data" which can be asynchronously processed on the main thread of conforming user agents. The interfaces and API defined in this specification can be used with other interfaces and APIs exposed to the web platform. The
In the example below, different code blocks handle progress, error, and success conditions.
2. Terminology and AlgorithmsWhen this specification says to terminate an algorithm
the user agent must terminate the algorithm after finishing the step it is on.
Asynchronous read methods defined in this specification may return before the algorithm in question is terminated,
and can be terminated by an The algorithms and steps in this specification use the following mathematical operations:
The term Unix Epoch is used in this specification to refer to the time 00:00:00 UTC on January 1 1970
(or 1970-01-01T00:00:00Z ISO 8601);
this is the same time that is conceptually "
The slice blob algorithm given a
Blob blob, start,
end, and contentType is used to refer to the following
steps and returns a new Blob containing the bytes ranging from the start parameter
up to but not including the end parameter. It must act as follows:
3. The Blob Interface and Binary DataA Each [
Their deserialization step, given serialized and value, are:
A
Blob blob has an associated get stream algorithm,
which runs these steps:
3.1. Constructors
The
Blob() constructor can be invoked with zero or more parameters.
When the Blob() constructor is invoked,
user agents must run the following steps:
3.1.1. Constructor ParametersThe
To process blob parts given a sequence of
BlobPart’s parts
and BlobPropertyBag options,
run the following steps:
To
convert line endings to native in a string s,
run the following steps:
Examples of constructor usage follow.
3.2. Attributes
3.3. Methods and Parameters3.3.1. The
|
| event handler content attribute | event handler event type |
|---|---|
onloadstart
| loadstart
|
onprogress
| progress
|
onabort
| abort
|
onerror
| error
|
onload
| load
|
onloadend
| loadend
|
FileReader object can be in one of 3 states.
The readyState attribute tells you in which state the object is:
EMPTY (numeric value 0)
The FileReader object has been constructed,
and there are no pending reads.
None of the read methods have been called.
This is the default state of a newly minted FileReader object,
until one of the read methods have been called on it.
LOADING (numeric value 1)
A File or Blob is being read.
One of the read methods is being processed,
and no error has occurred during the read.
DONE (numeric value 2)
The entire File or Blob has been read into memory,
OR a file read error occurred,
OR the read was aborted using abort().
The FileReader is no longer reading a File or Blob.
If readyState is set to DONE
it means at least one of the read methods have been called on this FileReader.
The FileReader interface makes available several asynchronous read methods—readAsArrayBuffer(), readAsBinaryString(), readAsText() and readAsDataURL(),
which read files into memory.
Note: If multiple concurrent read methods are called on the same FileReader object,
user agents throw an InvalidStateError on any of the read methods that occur
when readyState = LOADING.
(FileReaderSync makes available several synchronous read methods.
Collectively, the sync and async read methods of FileReader and FileReaderSync
are referred to as just read methods.)
readAsDataURL() methodThe readAsDataURL(blob) method,
when invoked, must initiate a read operation for blob with DataURL.
readAsText() methodThe readAsText(blob, encoding) method,
when invoked, must initiate a read operation for blob with Text and encoding.
readAsArrayBuffer()The readAsArrayBuffer(blob) method,
when invoked, must initiate a read operation for blob with ArrayBuffer.
readAsBinaryString() methodThe readAsBinaryString(blob) method,
when invoked, must initiate a read operation for blob with BinaryString.
Note: The use of readAsArrayBuffer() is preferred over
readAsBinaryString(), which is provided for backwards
compatibility.
abort() methodWhen the abort() method is called,
the user agent must run the steps below:
If this’s state is "empty"
or if this’s state is "done"
set this’s result to null
and terminate this algorithm.
If this’s state is "loading"
set this’s state to "done"
and set this’s result to null.
If there are any tasks from this on the file reading task source in an affiliated task queue, then remove those tasks from that task queue.
Terminate the algorithm for the read method being processed.
Fire a progress event called abort at this.
If this’s state is not "loading",
fire a progress event called loadend at this.
Blob has an associated package data algorithm,
given bytes, a type, a mimeType, and an optional encodingLabel,
which switches on type and runs the associated steps:
Return bytes as a DataURL [RFC2397] subject to the considerations below:
Use mimeType as part of the Data URL if it is not the empty string in keeping with the Data URL specification [RFC2397].
Otherwise, return a Data URL without a media-type. [RFC2397].
Better specify how the DataURL is generated. [Issue #104]
Let encoding be failure.
If the encodingLabel is present, set encoding to the result of getting an encoding from encodingLabel.
If encoding is failure:
Let type be the result of parse a MIME type given mimeType.
If type is not failure,
set encoding to the result of getting an encoding
from type’s parameters["charset"].
blob has a type attribute of text/plain;charset=utf-8
then getting an encoding is run using "utf-8" as the label.
Note that user agents must parse and extract the portion of the Charset Parameter
that constitutes a label of an encoding.
If encoding is failure, then set encoding to UTF-8.
Decode bytes using fallback encoding encoding, and return the result.
Return a new ArrayBuffer whose contents are bytes.
Return bytes as a binary string, in which every byte is represented by a code unit of equal value [0..255].
The FileReader object must be the event target for all events in this specification.
When this specification says to fire a progress event called e
(for some ProgressEvent e
at a given FileReader reader),
the following are normative:
The progress event e does not bubble. e.bubbles must be false [DOM]
The progress event e is NOT cancelable. e.cancelable must be false [DOM]
The following are the events that are fired at FileReader objects.
| Event name | Interface | Fired when… |
|---|---|---|
loadstart
| ProgressEvent
| When the read starts. |
progress
| ProgressEvent
| While reading (and decoding) blob
|
abort
| ProgressEvent
| When the read has been aborted.
For instance, by invoking the abort() method.
|
error
| ProgressEvent
| When the read has failed (see file read errors). |
load
| ProgressEvent
| When the read has successfully completed. |
loadend
| ProgressEvent
| When the request has completed (either in success or failure). |
This section is informative.
The following are invariants applicable to event firing for a given asynchronous read method in this specification:
Once a loadstart has been fired,
a corresponding loadend fires at completion of the read,
UNLESS any of the following are true:
the read method has been cancelled using abort()
and a new read method has been invoked
the event handler function for a load event initiates a new read
the event handler function for a error event initiates a new read.
Note: The events loadstart and loadend are not coupled in a one-to-one manner.
// In code of the sort... reader. readAsText( file); reader. onload= function (){ reader. readAsText( alternateFile);} ..... //... the loadend event must not fire for the first read reader. readAsText( file); reader. abort(); reader. onabort= function (){ reader. readAsText( updatedFile);} //... the loadend event must not fire for the first read
One progress event will fire when blob has been completely read into memory.
No progress event fires after any one of abort, load, and error have fired.
At most one of abort, load, and error fire for a given read.
Web Workers allow for the use of synchronous File or Blob read APIs,
since such reads on threads do not block the main thread.
This section defines a synchronous API, which can be used within Workers [Workers].
Workers can avail of both the asynchronous API (the FileReader object)
and the synchronous API (the FileReaderSync object).
FileReaderSync APIThis interface provides methods to synchronously read
File or Blob objects into memory.
[Exposed =(DedicatedWorker ,SharedWorker )]interface {FileReaderSync (); // Synchronously return stringsconstructor ArrayBuffer readAsArrayBuffer (Blob );blob DOMString readAsBinaryString (Blob );blob DOMString readAsText (Blob ,blob optional DOMString );encoding DOMString readAsDataURL (Blob ); };blob
When the FileReaderSync() constructor is invoked,
the user agent must return a new FileReaderSync object.
readAsText()The readAsText(blob, encoding) method,
when invoked, must run these steps:
Let stream be the result of calling get stream on blob.
Let reader be the result of getting a reader from stream.
Let promise be the result of reading all bytes from stream with reader.
Wait for promise to be fulfilled or rejected.
If promise fulfilled with a byte sequence bytes:
Return the result of package data given bytes, Text, blob’s type, and encoding.
Throw promise’s rejection reason.
readAsDataURL() methodThe readAsDataURL(blob) method,
when invoked, must run these steps:
Let stream be the result of calling get stream on blob.
Let reader be the result of getting a reader from stream.
Let promise be the result of reading all bytes from stream with reader.
Wait for promise to be fulfilled or rejected.
If promise fulfilled with a byte sequence bytes:
Return the result of package data given bytes, DataURL, and blob’s type.
Throw promise’s rejection reason.
readAsArrayBuffer() methodThe readAsArrayBuffer(blob) method,
when invoked, must run these steps:
Let stream be the result of calling get stream on blob.
Let reader be the result of getting a reader from stream.
Let promise be the result of reading all bytes from stream with reader.
Wait for promise to be fulfilled or rejected.
If promise fulfilled with a byte sequence bytes:
Return the result of package data given bytes, ArrayBuffer, and blob’s type.
Throw promise’s rejection reason.
readAsBinaryString() methodThe readAsBinaryString(blob) method,
when invoked, must run these steps:
Let stream be the result of calling get stream on blob.
Let reader be the result of getting a reader from stream.
Let promise be the result of reading all bytes from stream with reader.
Wait for promise to be fulfilled or rejected.
If promise fulfilled with a byte sequence bytes:
Return the result of package data given bytes, BinaryString, and blob’s type.
Throw promise’s rejection reason.
Note: The use of readAsArrayBuffer() is preferred over
readAsBinaryString(), which is provided for
backwards compatibility.
File read errors can occur when reading files from the underlying filesystem. The list below of potential error conditions is informative.
The File or Blob being accessed may not exist
at the time one of the asynchronous read methods or synchronous read methods are 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.
A File or Blob may be unreadable.
This may be due to permission problems that occur after a reference to a File or Blob has been acquired
(e.g. concurrent lock with another application).
Additionally, the snapshot state may have changed.
See NotReadableError.
User agents MAY determine that some files are unsafe for use within Web applications.
A file may change on disk since the original file selection,
thus resulting in an invalid read.
Additionally, some file and directory structures may be considered restricted by the underlying filesystem;
attempts to read from them may be considered a security violation.
See § 9 Security and Privacy Considerations and SecurityError.
This section is normative.
Error conditions can arise when reading a File or a Blob.
The read operation can terminate due to error conditions when reading a File or a Blob;
the particular error condition that causes the get stream algorithm to fail
is called a failure reason. A failure reason is one of
NotFound, UnsafeFile, TooManyReads, SnapshotState, or FileLock.
Synchronous read methods throw exceptions of the type in the table below if there has been an error owing to a particular failure reason.
Asynchronous read methods use the error attribute of the FileReader object,
which must return a DOMException object of the most appropriate type from the table below
if there has been an error owing to a particular failure reason,
or otherwise return null.
| Type | Description and Failure Reason |
|---|---|
NotFoundError
|
If the File or Blob resource could not be found at the time the read was processed,
this is the NotFound failure reason.
For asynchronous read methods the |
SecurityError
|
If:
For asynchronous read methods the This is a security error to be used in situations not covered by any other failure reason. |
NotReadableError
|
If:
For asynchronous read methods the |
This section defines a scheme for a URL used to refer to Blob
and MediaSource objects.
This section is informative.
Blob (or object) URLs are URLs like
blob:http://example.com/550e8400-e29b-41d4-a716-446655440000.
This enables integration of Blobs and MediaSources with other
APIs that are only designed to be used with URLs, such as the img element.
Blob URLs can also be used to navigate to as well as to trigger downloads
of locally generated data.
For this purpose two static methods are exposed on the URL interface,
createObjectURL(obj) and revokeObjectURL(url).
The first method creates a mapping from a URL to a Blob,
and the second method revokes said mapping.
As long as the mapping exist the Blob can’t be garbage collected,
so some care must be taken to revoke the URL as soon as the reference is no longer needed.
All URLs are revoked when the global that created the URL itself goes away.
Each user agent must maintain a blob URL store. A blob URL store is a map where keys are valid URL strings and values are blob URL Entries.
A blob URL entry consists of an object (of type
Blob or MediaSource), and an environment (an
environment settings object).
Note: Specifications have to use the obtain a blob object algorithm to access a blob URL entry’s object.
Keys in the blob URL store (also known as blob URLs)
are valid URL strings that when parsed
result in a URL with a scheme equal to "blob",
an empty host, and a path consisting of one element itself also a valid URL string.
top-level-navigation", or
"top-level-self-fetch" environment, perform the following steps. They return an
object.
Let isAuthorized be true.
If environment is an environment, then set isAuthorized to the result of checking for same-partition blob URL usage with blobUrlEntry and environment.
If isAuthorized is false, then return failure.
Return blobUrlEntry’s object.
Let result be the empty string.
Append the string "blob:" to result.
Let settings be the current settings object
Let origin be settings’s origin.
Let serialized be the ASCII serialization of origin.
If serialized is "null", set it to an implementation-defined value.
Append serialized to result.
Append U+0024 SOLIDUS (/) to result.
Generate a UUID [RFC4122] as a string and append it to result.
Return result.
blob:https://example.org/40a5fb5a-d56d-4a33-b4e2-0acf6a8e5f64.
Let store be the user agent’s blob URL store.
Let url be the result of generating a new blob URL.
Let entry be a new blob URL entry consisting of object and the current settings object.
Set store[url] to entry.
Return url.
Let store be the user agent’s blob URL store;
Let url string be the result of serializing url.
Remove store[url string].
Let store be the user agent’s blob URL store.
Let url string be the result of serializing url with the exclude fragment flag set.
If store[url string] exists, return store[url string]; otherwise return failure.
Futher requirements for the parsing and fetching model for blob URLs are defined in the [URL] and [Fetch] specifications.
This section is informative.
The origin of a blob URL is always the same as that of the environment that created the URL, as long as the URL hasn’t been revoked yet. This is achieved by the [URL] spec looking up the URL in the blob URL store when parsing a URL, and using that entry to return the correct origin.
If the URL was revoked the serialization of the origin will still remain the same as the serialization of the origin of the environment that created the blob URL, but for opaque origins the origin itself might be distinct. This difference isn’t observable though, since a revoked blob URL can’t be resolved/fetched anymore anyway.
Blob URLs can only be fetched from environments where the storage key matches that of the environment where the blob URL was created. Top-level blob URL navigations are not subject to this restriction.
Let blobStorageKey be the result of obtaining a storage key for non-storage purposes with blobUrlEntry’s environment.
Let environmentStorageKey be the result of obtaining a storage key for non-storage purposes with environment.
If blobStorageKey is not equal to environmentStorageKey, then return false.
Return true.
This specification extends the unloading document cleanup steps with the following steps:
Let environment be the Document’s relevant settings object.
Let store be the user agent’s blob URL store;
Remove from store any entries for which the value’s environment is equal to environment.
This needs a similar hook when a worker is unloaded.
Blob URLs are created and revoked using static methods exposed on the URL object.
Revocation of a blob URL decouples the blob URL from the resource it refers to,
and if it is dereferenced after it is revoked,
user agents must act as if a network error has occurred.
This section describes a supplemental interface to the URL specification [URL]
and presents methods for blob URL creation and revocation.
[Exposed =(Window ,DedicatedWorker ,SharedWorker )]partial interface URL {static DOMString createObjectURL ((Blob or MediaSource ));obj static undefined revokeObjectURL (DOMString ); };url
createObjectURL(obj) static method must
return the result of adding an entry to the blob URL store for obj.
revokeObjectURL(url) static method must run these steps:
Let urlRecord be the result of parsing url.
If urlRecord’s scheme is not "blob", return.
Let entry be urlRecord’s blob URL entry.
If entry is null, then return.
Let isAuthorized be the result of checking for same-partition blob URL usage with entry and the current settings object.
If isAuthorized is false, then return.
Note: This means that rather than throwing some kind of error, attempting to revoke a URL that isn’t registered or that was registered from an environment in a different storage partition will silently fail. User agents might display a message on the error console if this happens.
Note: Attempts to dereference url after it has been revoked will result in a network error. Requests that were started before the url was revoked should still succeed.
window1 and window2 are separate,
but in the same origin;
window2 could be an iframe inside window1.
myurl= window1. URL. createObjectURL( myblob); window2. URL. revokeObjectURL( myurl);
Since a user agent has one global blob URL store,
it is possible to revoke an object URL from a different window than from which it was created.
The URL. call
ensures that subsequent dereferencing of revokeObjectURL()myurl
results in a the user agent acting as if a network error has occurred.
Blob URLs are strings that are used to fetch Blob objects,
and can persist for as long as the document from which they were minted
using URL.—see § 8.3.3 Lifetime of blob URLs.createObjectURL()
This section gives sample usage of creation and revocation of blob URLs with explanations.
img elements [HTML] refer to the same blob URL:
url= URL. createObjectURL( blob); img1. src= url; img2. src= url;
URL.revokeObjectURL() is explicitly called.
var blobURLref= URL. createObjectURL( file); img1= new Image(); img2= new Image(); // Both assignments below work as expected img1. src= blobURLref; img2. src= blobURLref; // ... Following body load // Check if both images have loaded if ( img1. complete&& img2. complete) { // Ensure that subsequent refs throw an exception URL. revokeObjectURL( blobURLref); } else { msg( "Images cannot be previewed!" ); // revoke the string-based reference URL. revokeObjectURL( blobURLref); }
The example above allows multiple references to a single blob URL,
and the web developer then revokes the blob URL string after both image objects have been loaded.
While not restricting number of uses of the blob URL offers more flexibility,
it increases the likelihood of leaks;
developers should pair it with a corresponding call to URL..revokeObjectURL()
This section is informative.
This specification allows web content to read files from the underlying file system,
as well as provides a means for files to be accessed by unique identifiers,
and as such is subject to some security considerations.
This specification also assumes that the primary user interaction is with the <input type="file"/> element of HTML forms [HTML],
and that all files that are being read by FileReader objects have first been selected by the user.
Important security considerations include preventing malicious file selection attacks (selection looping),
preventing access to system-sensitive files,
and guarding against modifications of files on disk after a selection has taken place.
During file selection, a user may be bombarded with the file picker associated with <input type="file"/>
(in a "must choose" loop that forces selection before the file picker is dismissed)
and a user agent may prevent file access to any selections by making the FileList object returned be of size 0.
(e.g. files in /usr/bin, password files, and other native operating system executables)
typically should not be exposed to web content,
and should not be accessed via blob URLs.
User agents may throw a SecurityError exception for synchronous read methods,
or return a SecurityError exception for asynchronous reads.
This section is provisional; more security data may supplement this in subsequent drafts.
This section covers what the requirements are for this API, as well as illustrates some use cases. This version of the API does not satisfy all use cases; subsequent versions may elect to address these.
Once a user has given permission, user agents should provide the ability to read and parse data directly from a local file programmatically.
Data should be able to be stored locally so that it is available for later use, which is useful for offline data access for web applications.
text/calendar file is parsed in the browser,
allowing the user to merge the files to one calendar view.
The user wants to then save the file back to his local calendar file (using "Save As"?).
The user can also send the integrated calendar file back to the server calendar store asynchronously.
User agents should provide the ability to save a local file programmatically given an amount of data and a file name.
Note: While this specification doesn’t provide an explicit API call to trigger downloads,
the HTML5 specification has addressed this.
The download attribute of the a element initiates a download,
saving a File with the name specified.
The combination of this API and the download attribute on a elements
allows for the creation of files within web applications,
and the ability to save them locally.
User agents should provide a streamlined programmatic ability to send data from a file to a remote server that works more efficiently than form-based uploads today.
User agents should provide an API exposed to script that exposes the features above. The user is notified by UI anytime interaction with the file system takes place, giving the user full ability to cancel or abort the transaction. The user is notified of any file selections, and can cancel these. No invocations to these APIs occur silently without user intervention.
This specification was originally developed by the SVG Working Group. Many thanks to Mark Baker and Anne van Kesteren for their feedback.
Thanks to Robin Berjon, Jonas Sicking and Vsevolod Shmyroff for editing the original specification.
Special thanks to Olli Pettay, Nikunj Mehta, Garrett Smith, Aaron Boodman, Michael Nordman, Jian Li, Dmitry Titov, Ian Hickson, Darin Fisher, Sam Weinig, Adrian Bateman and Julian Reschke.
Thanks to the W3C WebApps WG, and to participants on the [email protected] listserv