1. Introduction
This 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 File interface represents file data typically obtained from the underlying file system,
and the Blob interface
("Binary Large Object" - a name originally introduced to web APIs in Google Gears)
represents immutable raw data. File or Blob reads should happen asynchronously on the main thread,
with an optional synchronous API used within threaded web applications.
An asynchronous API for reading files prevents blocking and UI "freezing" on a user agent’s main thread.
This specification defines an asynchronous API based on an event model to read and access a File or Blob’s data.
A FileReader object provides asynchronous read methods to access that file’s data
through event handler content attributes and the firing of events.
The use of events and event handlers allows separate code blocks the ability
to monitor the progress of the read (which is particularly useful for remote drives or mounted drives,
where file access performance may vary from local drives)
and error conditions that may arise during reading of a file.
An example will be illustrative.
function startRead() { // obtain input element through DOM var file = document.getElementById('file').files[0]; if(file){ getAsText(file); } } function getAsText(readFile) { var reader = new FileReader(); // Read file into memory as UTF-16 reader.readAsText(readFile, "UTF-16"); // Handle progress, success, and errors reader.onprogress = updateProgress; reader.onload = loaded; reader.onerror = errorHandler; } function updateProgress(evt) { if (evt.lengthComputable) { // evt.loaded and evt.total are ProgressEvent properties var loaded = (evt.loaded / evt.total); if (loaded < 1) { // Increase the prog bar length // style.width = (loaded * 200) + "px"; } } } function loaded(evt) { // Obtain the read file data var fileString = evt.target.result; // Handle UTF-16 file dump if(utils.regexp.isChinese(fileString)) { //Chinese Characters + Name validation } else { // run other charset test } // xhr.send(fileString) } function errorHandler(evt) { if(evt.target.error.name == "NotReadableError") { // The file could not be read } }
2. Conformance
Everything in this specification is normative except for examples and sections marked as being informative.
The keywords “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL 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:
- conforming user agent#dfn-conforming-implementationReferenced in:2. Conformance2.1. Dependencies (2) (3) (4) (5)
-
A user agent is considered to be a conforming user agent if it satisfies all of the MUST-, REQUIRED-,
and SHALL-level criteria in this specification that apply to implementations.
This specification uses both the terms "conforming user agent" and "user agent" to refer to this product class.
User agents may implement algorithms in this specifications in any way desired, so long as the end result is indistinguishable from the result that would be obtained from the specification’s algorithms.
User agents that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL] as this specification uses that specification and terminology.
2.1. Dependencies
This specification relies on underlying specifications.
- DOM
- A conforming user agent must support at least the subset of the functionality defined in DOM4 that this specification relies upon;
in particular, it must support
EventTarget. - Progress Events
- A conforming user agent must support the Progress Events specification. Data access on read operations is enabled via Progress Events. [PROGRESS-EVENTS]
- HTML
- A conforming user agent must support at least the subset of the functionality defined in HTML that this specification relies upon; in particular, it must support event loops and event handler content attributes. [HTML]
- Web IDL
- A conforming user agent must also be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification. [WebIDL]
- Typed Arrays
- A conforming user agent must support the Typed Arrays specification [TypedArray].
Parts of this specification rely on the Web Workers specification; for those parts of this specification, the Web Workers specification is a normative dependency. [Workers]
3. Terminology and Algorithms
When this specification says to terminate an algorithm#terminate-an-algorithmReferenced in:4.3.2.
The close method7.1.
The Read Operation (2) (3)7.3.4.2.
The readAsDataURL() method (2) (3)7.3.4.3.
The readAsText() method (2) (3)7.3.4.4.
The readAsArrayBuffer() method (2) (3)7.3.4.5.
Error Steps7.3.4.6.
The abort() method (2)7.6.1.2.
The readAsText() method (2) (3)7.6.1.3.
The readAsDataURL() method (2) (3)7.6.1.4.
The readAsArrayBuffer() method (2) (3) 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 abort() call.
The algorithms and steps in this specification use the following mathematical operations:
-
max(a,b) returns the maximum of a and b, and is always performed on integers as they are defined in WebIDL [WebIDL]; in the case of max(6,4) the result is 6. This operation is also defined in ECMAScript [ECMA-262].
-
min(a,b) returns the minimum of a and b, and is always performed on integers as they are defined in WebIDL [WebIDL]; in the case of min(6,4) the result is 4. This operation is also defined in ECMAScript [ECMA-262].
-
Mathematical comparisons such as < (less than), ≤ (less than or equal to), and > (greater than) are as in ECMAScript [ECMA-262].
The term Unix Epoch#UnixEpochReferenced in:5.1.
Constructor (2)5.2.
Attributes (2) 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 "0" in ECMA-262 [ECMA-262].
4. The Blob Interface and Binary Data
A Blob object refers to a byte sequence,
and has a size attribute which is the total number of bytes in the byte sequence,
and a type attribute,
which is an ASCII-encoded string in lower case representing the media type of the byte sequence.
A Blob must have a readability state#readabilityStateReferenced in:4.
The Blob Interface and Binary Data (2)4.1.
Constructors (2)4.2.
Attributes (2) (3)4.3.1.
The slice method (2) (3)4.3.2.
The close method (2)5.1.
Constructor7.1.
The Read Operation7.3.4.2.
The readAsDataURL() method7.3.4.3.
The readAsText() method7.3.4.4.
The readAsArrayBuffer() method9.5.1.
Methods and Parameters (2) (3),
which is one of OPENED or CLOSED.
A Blob that refers to a byte sequence,
including one of 0 bytes,
is said to be in the OPENED#dfn-openStateReferenced in:4.
The Blob Interface and Binary Data4.1.
Constructors (2)4.2.
Attributes5.1.
Constructor readability state.
A Blob is said to be closed#closedReferenced in:4.
The Blob Interface and Binary Data4.3.2.
The close method9.4.3.
Network Errors if its close() method has been called.
A Blob that is closed is said to be in the CLOSED#dfn-closedStateReferenced in:4.
The Blob Interface and Binary Data4.2.
Attributes (2) (3)4.3.2.
The close method (2)7.1.
The Read Operation7.3.4.2.
The readAsDataURL() method7.3.4.3.
The readAsText() method7.3.4.4.
The readAsArrayBuffer() method9.5.1.
Methods and Parameters (2) (3) readability state.
Each Blob must have an internal snapshot state#snapshot-stateReferenced in:4.
The Blob Interface and Binary Data5.
The File Interface (2) (3) (4)8.
Errors and Exceptions8.1.
Throwing an Exception or Returning an Error (2),
which must be initially set to the state of the underlying storage,
if any such underlying storage exists,
and must be preserved through structured clone.
Further normative definition of snapshot state can be found for Files.
[Constructor#dom-blob-blobReferenced in:4.1. Constructors (2)4.1.1. Constructor Parameters, Constructor(sequence<BlobPart> blobParts, optional BlobPropertyBag options), Exposed=(Window,Worker)] interface Blob#dfn-BlobReferenced in:1. Introduction (2) (3)4. The Blob Interface and Binary Data (2) (3) (4) (5) (6) (7) (8)4.1. Constructors (2) (3) (4) (5) (6)4.1.1. Constructor Parameters (2)4.2. Attributes (2) (3) (4) (5) (6) (7) (8)4.3.1. The slice method (2) (3) (4) (5) (6) (7)4.3.2. The close method (2)5. The File Interface (2)5.1. Constructor (2) (3)5.1.1. Constructor Parameters5.2. Attributes7.1. The Read Operation (2) (3) (4) (5)7.2. The File Reading Task Source7.3. The FileReader API (2) (3)7.3.3. FileReader States (2) (3)7.3.4.1. The result attribute (2) (3) (4) (5) (6)7.3.4.7. Blob Parameters (2) (3)7.4. Determining Encoding7.6. Reading on Threads7.6.1. The FileReaderSync API (2) (3) (4)8. Errors and Exceptions (2) (3)8.1. Throwing an Exception or Returning an Error (2) (3) (4) (5) (6)9. A URL for Blob and File reference9.1. Requirements for a New Scheme (2) (3) (4) (5)9.2. Discussion of Existing Schemes (2)9.3. The Blob URL (2)9.4.2. Response Headers (2)9.4.4. Sample Request and Response Headers (2)9.5. Creating and Revoking a Blob URL (2)9.5.1. Methods and Parameters (2) (3) (4) (5)9.5.2. Examples of Blob URL Creation and Revocation9.6. Lifetime of Blob URLs (2) (3) (4) (5) { readonly attribute unsigned long long size; readonly attribute DOMString type; readonly attribute boolean isClosed; //slice Blob into byte-ranged chunks Blob slice([Clamp] optional long long start, [Clamp] optional long long end, optional DOMString contentType); void close(); }; dictionary BlobPropertyBag#dfn-BlobPropertyBagReferenced in:4. The Blob Interface and Binary Data4.1.1. Constructor Parameters { DOMString type = ""; }; typedef (ArrayBuffer or ArrayBufferView or Blob or DOMString) BlobPart#typedefdef-blobpartReferenced in:4. The Blob Interface and Binary Data5. The File Interface;
4.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:
-
If invoked with zero parameters, return a new
Blobobject with its readability state set toOPENED, consisting of 0 bytes, withsizeset to 0, and withtypeset to the empty string. -
Otherwise, the constructor is invoked with a
blobPartssequence. Let a be that sequence. -
Let bytes be an empty sequence of bytes.
-
Let length be a’s length. For 0 ≤ i < length, repeat the following steps:
-
Let element be the ith element of a.
-
If element is a
DOMString, run the following substeps:-
Let s be the result of converting element to a sequence of Unicode characters [Unicode] using the algorithm for doing so in WebIDL [WebIDL].
-
Encode s as utf-8 and append the resulting bytes to bytes.
Note: The algorithm from WebIDL [WebIDL] replaces unmatched surrogates in an invalid utf-16 string with U+FFFD replacement characters. Scenarios exist when the
Blobconstructor may result in some data loss due to lost or scrambled character sequences.
-
-
If element is an
ArrayBufferView, convert it to a sequence ofbyteLengthbytes from the underlyingArrayBuffer, starting at thebyteOffsetof theArrayBufferView, and append those bytes to bytes. -
If element is an
ArrayBuffer, convert it to a sequence ofbyteLengthbytes, and append those bytes to bytes. -
If element is a
Blob, append the bytes it represents to bytes. Thetypeof theBlobarray element is ignored.
-
-
If the
typemember of the optionaloptionsargument is provided and is not the empty string, run the following sub-steps:-
Let t be the
typedictionary member. If t contains any characters outside the range U+0020 to U+007E, then set t to the empty string and return from these substeps. -
Convert every character in t to lowercase using the "converting a string to ASCII lowercase" algorithm.
-
-
Return a
Blobobject with its readability state set toOPENED, referring to bytes as its associated byte sequence, with itssizeset to the length of bytes, and itstypeset to the value of t from the substeps above.Note: The type t of a
Blobis considered a parsable MIME type if the ASCII-encoded string representing the Blob object’s type, when converted to a byte sequence, does not return undefined for the parse a MIME type algorithm.
4.1.1. Constructor Parameters
The Blob() constructor can be invoked with the parameters below:
- A
blobParts#dfn-blobPartsReferenced in:4. The Blob Interface and Binary Data4.1. Constructorssequence -
which takes any number of the following types of elements, and in any order:
-
ArrayBufferelements. -
ArrayBufferViewelements. -
Blobelements. -
DOMStringelements.
-
- An optional
BlobPropertyBag -
which takes one member:
-
type#dfn-BPtypeReferenced in:4. The Blob Interface and Binary Data4.1. Constructors (2), the ASCII-encoded string in lower case representing the media type of the
Blob. Normative conditions for this member are provided in the §4.1 Constructors.
-
// Create a new Blob object var a = new Blob(); // Create a 1024-byte ArrayBuffer // buffer could also come from reading a File var buffer = new ArrayBuffer(1024); // Create ArrayBufferView objects based on buffer var shorts = new Uint16Array(buffer, 512, 128); var bytes = new Uint8Array(buffer, shorts.byteOffset + shorts.byteLength); var b = new Blob(["foobarbazetcetc" + "birdiebirdieboo"], {type: "text/plain;charset=utf-8"}); var c = new Blob([b, shorts]); var a = new Blob([b, c, bytes]); var d = new Blob([buffer, b, c, bytes]);
4.2. Attributes
- size#dfn-sizeReferenced in:4. The Blob Interface and Binary Data (2)4.1. Constructors (2)4.2. Attributes4.3.1. The slice method (2) (3)5.1. Constructor7.1. The Read Operation9.4.2. Response Headers , of type unsigned long long, readonly
- Returns the size of the byte sequence in number of bytes.
On getting, conforming user agents must return the total number of bytes that can be read by a
FileReaderorFileReaderSyncobject, or 0 if theBlobhas no bytes to be read. If theBlobhas a readability state ofCLOSEDthensizemust return 0. - type#dfn-typeReferenced in:4. The Blob Interface and Binary Data (2)4.1. Constructors (2) (3)4.2. Attributes (2) (3)4.3.1. The slice method (2)5. The File Interface (2)5.1. Constructor (2)7.3.4.2. The readAsDataURL() method (2)7.4. Determining Encoding (2)7.6.1.3. The readAsDataURL() method (2)9.4.2. Response Headers9.4.4. Sample Request and Response Headers , of type DOMString, readonly
-
The ASCII-encoded string in lower case representing the media type of the
Blob. On getting, user agents must return the type of aBlobas an ASCII-encoded string in lower case, such that when it is converted to a byte sequence, it is a parsable MIME type, or the empty string – 0 bytes – if the type cannot be determined.The
typeattribute can be set by the web application itself through constructor invocation and through theslice()call; in these cases, further normative conditions for this attribute are in §4.1 Constructors, §5.1 Constructor, and §4.3.1 The slice method respectively. User agents can also determine thetypeof aBlob, especially if the byte sequence is from an on-disk file; in this case, further normative conditions are in the file type guidelines. - isClosed#dfn-isClosedReferenced in:4. The Blob Interface and Binary Data , of type boolean, readonly
- The boolean value that indicates whether the
Blobis in theCLOSEDreadability state. On getting, user agents must returnfalseif theBlobis in theOPENEDreadability state, andtrueif theBlobis in theCLOSEDreadability state as a result of theclose()method being called.
Note: Use of the type attribute informs the encoding determination and parsing the Content-Type header when dereferencing Blob URLs.
4.3. Methods and Parameters
4.3.1. The slice method
The slice()#dfn-sliceReferenced in:4.
The Blob Interface and Binary Data4.2.
Attributes4.3.1.
The slice method (2) (3) (4) (5) (6) (7) (8) method
returns a new Blob object with bytes ranging from
the optional start parameter
upto but not including the optional end parameter,
and with a type attribute that is the value of the optional contentType parameter.
It must act as follows:
-
Let O be the
Blobcontext object on which theslice()method is being called. -
The optional start#dfn-startReferenced in:4. The Blob Interface and Binary Data4.3.1. The slice method (2) (3) (4) (5) parameter is a value for the start point of a
slice()call, and must be treated as a byte-order position, with the zeroth position representing the first byte. User agents must processslice()withstartnormalized according to the following: -
The optional end#dfn-endReferenced in:4. The Blob Interface and Binary Data4.3.1. The slice method (2) (3) (4) parameter is a value for the end point of a
slice()call. User agents must processslice()withendnormalized according to the following: -
The optional contentType#dfn-contentTypeBlobReferenced in:4. The Blob Interface and Binary Data4.3.1. The slice method (2) (3) (4) parameter is used to set the ASCII-encoded string in lower case representing the media type of the Blob. User agents must process the
slice()withcontentTypenormalized according to the following:- If the
contentTypeparameter is not provided, let relativeContentType be set to the empty string . -
Else let relativeContentType be set to
contentTypeand run the substeps below:-
If relativeContentType contains any characters outside the range of U+0020 to U+007E, then set relativeContentType to the empty string and return from these substeps.
-
Convert every character in relativeContentType to lower case using the "Converting a string to ASCII lowercase" algorithm.
-
- If the
-
Let span be
max((relativeEnd - relativeStart), 0). -
Return a new
Blobobject S with the following characteristics:-
S has a readability state equal to that of O’s readability state.
Note: The readability state of the context object is retained by the
Blobobject returned by theslice()call; this has implications on whether the returnedBlobis actually usable for read operations or as a Blob URL. - S refers to span consecutive bytes from O, beginning with the byte at byte-order position relativeStart.
- S.
size= span. -
S.
type= relativeContentType.Note: The type t of a
Blobis considered a parsable MIME type if the ASCII-encoded string representing the Blob object’s type, when converted to a byte sequence, does not return undefined for the parse a MIME type algorithm.
-
S has a readability state equal to that of O’s readability state.
slice() calls possible. Since the File interface inherits from the Blob interface, examples are based on the use of the File interface.
// obtain input element through DOM var file = document.getElementById('file').files[0]; if(file) { // create an identical copy of file // the two calls below are equivalent var fileClone = file.slice(); var fileClone2 = file.slice(0, file.size); // slice file into 1/2 chunk starting at middle of file // Note the use of negative number var fileChunkFromEnd = file.slice(-(Math.round(file.size/2))); // slice file into 1/2 chunk starting at beginning of file var fileChunkFromStart = file.slice(0, Math.round(file.size/2)); // slice file from beginning till 150 bytes before end var fileNoMetadata = file.slice(0, -150, "application/experimental"); }
4.3.2. The close method
The close()#dfn-closeReferenced in:4.
The Blob Interface and Binary Data (2)4.2.
Attributes7.6.1.2.
The readAsText() method7.6.1.3.
The readAsDataURL() method7.6.1.4.
The readAsArrayBuffer() method method is said to close a Blob,
and must act as follows on the Blob on which the method has been called:
-
If the readability state of the context object is
CLOSED, terminate this algorithm. -
Otherwise, set the readability state of the context object to
CLOSED. -
If the context object has an entry in the Blob URL Store, remove the entry that corresponds to the context object.
5. The File Interface
A File object is a Blob object with a name attribute, which is a string;
it can be created within the web application via a constructor,
or is a reference to a byte sequence from a file from the underlying (OS) file system.
If a File object is a reference to a byte sequence originating from a file on disk,
then its snapshot state should be set to the state of the file on disk at the time the File object is created.
Note: This is a non-trivial requirement to implement for user agents,
and is thus not a must but a should [RFC2119].
User agents should endeavor to have a File object’s snapshot state set to the state of the underlying storage on disk at the time the reference is taken.
If the file is modified on disk following the time a reference has been taken,
the File's snapshot state will differ from the state of the underlying storage.
User agents may use modification time stamps and other mechanisms to maintain snapshot state,
but this is left as an implementation detail.
When a File object refers to a file on disk,
user agents must return the type of that file,
and must follow the file type guidelines#file-type-guidelinesReferenced in:4.2.
Attributes below:
-
User agents must return the
typeas an ASCII-encoded string in lower case, such that when it is converted to a corresponding byte sequence, it is a parsable MIME type, or the empty string – 0 bytes – if the type cannot be determined. -
When the file is of type
text/plainuser agents must NOT append a charset parameter to the dictionary of parameters portion of the media type [MIMESNIFF]. -
User agents must not attempt heuristic determination of encoding, including statistical methods.
[Constructor#dom-file-fileReferenced in:5.1. Constructor5.1.1. Constructor Parameters(sequence<BlobPart> fileBits, [EnsureUTF16] DOMString fileName, optional FilePropertyBag options), Exposed=(Window,Worker)] interface File#dfn-fileReferenced in:1. Introduction (2) (3)4. The Blob Interface and Binary Data4.3.1. The slice method (2)5. The File Interface (2) (3) (4) (5) (6)5.1. Constructor (2) (3)5.1.1. Constructor Parameters (2)5.2. Attributes (2) (3) (4)6. The FileList Interface (2)6.2. Methods and Parameters (2) (3) (4) (5)7.2. The File Reading Task Source7.3.3. FileReader States (2) (3)7.3.4.1. The result attribute (2) (3) (4) (5)7.3.4.7. Blob Parameters7.6. Reading on Threads7.6.1. The FileReaderSync API8. Errors and Exceptions (2) (3)8.1. Throwing an Exception or Returning an Error (2) (3) (4) (5) (6)9. A URL for Blob and File reference9.3. The Blob URL (2)9.4.2. Response Headers (2) (3)9.5.1. Methods and Parameters11. Requirements and Use Cases : Blob { readonly attribute DOMString name; readonly attribute long long lastModified; }; dictionary FilePropertyBag#dfn-FilePropertyBagReferenced in:5. The File Interface5.1. Constructor5.1.1. Constructor Parameters { DOMString type = ""; long long lastModified; };
5.1. Constructor
The File constructor is invoked with two or three parameters,
depending on whether the optional dictionary parameter is used.
When the File() constructor is invoked,
user agents must run the following steps:
-
Let a be the
fileBitssequence argument. Let bytes be an empty sequence of byte. Let length be a’s length. For 0 ≤ i < length, repeat the following steps:-
Let element be the i’th element of a.
-
If element is a
DOMString, run the following substeps:-
Let s be the result of converting element to a sequence of Unicode characters [Unicode] using the algorithm for doing so in WebIDL [WebIDL].
Note: The algorithm from WebIDL [WebIDL] replaces unmatched surrogates in an invalid utf-16 string with U+FFFD replacement characters. Scenarios exist when the
Blobconstructor may result in some data loss due to lost or scrambled character sequences. -
-
If element is an
ArrayBufferView, convert it to a sequence ofbyteLengthbytes from the underlyingArrayBuffer, starting at thebyteOffsetof theArrayBufferView, and append those bytes to bytes. -
If element is an
ArrayBuffer, convert it to a sequence ofbyteLengthbytes, and append those bytes to bytes. -
If element is a
Blob, append the bytes it represents to bytes. Thetypeof theBlobargument must be ignored.
-
-
Let n be a new string of the same size as the
fileNameargument to the constructor. Copy every character fromfileNameto n, replacing any "/" character (U+002F SOLIDUS) with a ":" (U+003A COLON).Note: Underlying OS filesystems use differing conventions for file name; with constructed files, mandating UTF-16 lessens ambiquity when file names are converted to byte sequences.
-
If the optional
FilePropertyBagdictionary argument is used, then run the following substeps:-
If the
typemember is provided and is not the empty string, let t be set to thetypedictionary member. If t contains any characters outside the range U+0020 to U+007E, then set t to the empty string and return from these substeps. -
Convert every character in t to lowercase using the "converting a string to ASCII lowercase" algorithm.
-
If the
lastModifiedmember is provided, let d be set to thelastModifieddictionary member. If it is not provided, set d to the current date and time represented as the number of milliseconds since the Unix Epoch (which is the equivalent ofDate.now()[ECMA-262]).Note: Since ECMA-262
Dateobjects convert tolong longvalues representing the number of milliseconds since the Unix Epoch, thelastModifiedmember could be aDateobject [ECMA-262].
-
-
Return a new
Fileobject F such that:-
F has a readability state of
OPENED. -
F refers to the bytes byte sequence.
-
F.
sizeis set to the number of total bytes in bytes. -
F.
nameis set to n. -
F.
typeis set to t.Note: The type t of a
Fileis considered a parsable MIME type if the ASCII-encoded string representing the File object’s type, when converted to a byte sequence, does not return undefined for the parse a MIME type algorithm. -
F.
lastModifiedis set to d.
-
5.1.1. Constructor Parameters
The File() constructor can be invoked with the parameters below:
- A
fileBits#dfn-fileBitsReferenced in:5. The File Interface5.1. Constructorsequence -
which takes any number of the following elements, and in any order:
-
ArrayBufferelements. -
ArrayBufferViewelements. -
DOMStringelements.
-
- A
fileName#dfn-fileNameReferenced in:5. The File Interface5.1. Constructor (2) parameter - A
DOMStringparameter representing the name of the file; normative conditions for this constructor parameter can be found in §5.1 Constructor. - An optional
FilePropertyBagdictionary -
which takes the following members:
-
An optional type#dfn-FPtypeReferenced in:5. The File Interface5.1. Constructor (2) member; the ASCII-encoded string in lower case representing the media type of the
File. Normative conditions for this member are provided in §5.1 Constructor. -
An optional lastModified#dfn-FPdateReferenced in:5. The File Interface5.1. Constructor (2) (3) member, which must be a
long long; normative conditions for this member are provided in §5.1 Constructor.
-
5.2. Attributes
- name#dfn-nameReferenced in:5. The File Interface (2)5.1. Constructor9.4.2. Response Headers (2) (3) , of type DOMString, readonly
- The name of the file.
On getting, this must return the name of the file as a string.
There are numerous file name variations and conventions used by different underlying OS file systems;
this is merely the name of the file, without path information.
On getting, if user agents cannot make this information available,
they must return the empty string.
If a
Fileobject is created using a constructor, further normative conditions for this attribute are found in §5.1 Constructor. - lastModified#dfn-lastModifiedReferenced in:5. The File Interface5.1. Constructor , of type long long, readonly
- The last modified date of the file.
On getting, if user agents can make this information available,
this must return a
long longset to the time the file was last modified as the number of milliseconds since the Unix Epoch. If the last modification date and time are not known, the attribute must return the current date and time as along longrepresenting the number of milliseconds since the Unix Epoch; this is equivalent toDate.now()[ECMA-262]. If aFileobject is created using a constructor, further normative conditions for this attribute are found in §5.1 Constructor.
The File interface is available on objects that expose an attribute of type FileList;
these objects are defined in HTML [HTML].
The File interface, which inherits from Blob, is immutable,
and thus represents file data that can be read into memory at the time a read operation is initiated.
User agents must process reads on files that no longer exist at the time of read as errors,
throwing a NotFoundError exception
if using a FileReaderSync on a Web Worker [Workers] or firing an error event
with the error attribute returning a NotFoundError DOMError.
var file = document.getElementById("filePicker").files[0]; var date = new Date(file.lastModified); println("You selected the file " + file.name + " which was modified on " + date.toDateString() + " ."); ... // Generate a file with a specific last modified date var d = new Date(2013, 12, 5, 16, 23, 45, 600); var generatedFile = new File(["Rough Draft ...."], "Draft1.txt", {type: "text/plain"; lastModified: d}) ...
6. The FileList Interface
Note: The FileList interface should be considered "at risk"
since the general trend on the Web Platform is to replace such interfaces
with the Array platform object in ECMAScript [ECMA-262].
In particular, this means syntax of the sort filelist.item(0) is at risk;
most other programmatic use of FileList is unlikely to be affected by the eventual migration to an Array type.
This interface is a list of File objects.
[Exposed=(Window,Worker)]
interface FileList#dfn-filelistReferenced in:5.2.
Attributes6.
The FileList Interface (2)6.1.
Attributes6.2.
Methods and Parameters (2) (3) (4) (5) (6)7.3.4.7.
Blob Parameters10.
Security Considerations {
getter File? item(unsigned long index);
readonly attribute unsigned long length;
};
<input type="file"> element within a form,
and then accessing selected files.
// uploadData is a form element // fileChooser is input element of type 'file' var file = document.forms['uploadData']['fileChooser'].files[0]; // alternative syntax can be // var file = document.forms['uploadData']['fileChooser'].files.item(0); if(file) { // Perform file ops }
6.1. Attributes
- length#dfn-lengthReferenced in:6. The FileList Interface , of type unsigned long, readonly
- must return the number of files in the
FileListobject. If there are no files, this attribute must return 0.
6.2. Methods and Parameters
- item(index)#dfn-itemReferenced in:6. The FileList Interface
-
must return the indexth
Fileobject in theFileList. If there is no indexthFileobject in theFileList, then this method must returnnull.index#dfn-indexReferenced in:6. The FileList Interface must be treated by user agents as value for the position of a
Fileobject in theFileList, with 0 representing the first file. Supported property indices are the numbers in the range zero to one less than the number ofFileobjects represented by theFileListobject. If there are no suchFileobjects, then there are no supported property indices.
Note: The HTMLInputElement interface has a readonly attribute of type FileList,
which is what is being accessed in the above example.
Other interfaces with a readonly attribute of type FileList include the DataTransfer interface.
7. Reading Data
7.1. The Read Operation
The algorithm below defines a read operation,
which takes a Blob and a synchronous flag as input,
and reads bytes into a byte stream
which is returned as the result of the read operation,
or else fails along with a failure reason.
Methods in this specification invoke the read operation with the synchronous flag either set or unset.
The synchronous flag#synchronousFlagReferenced in:7.1. The Read Operation (2) (3) (4) (5) (6) (7) (8)7.6.1.2. The readAsText() method7.6.1.3. The readAsDataURL() method7.6.1.4. The readAsArrayBuffer() method determines if a read operation is synchronous or asynchronous, and is unset by default. Methods may set it. If it is set, the read operation takes place synchronously. Otherwise, it takes place asynchronously.
To perform a read operation#readOperationReferenced in:4.3.1.
The slice method5.2.
Attributes7.1.
The Read Operation (2) (3) (4) (5) (6) (7) (8) (9) (10)7.3.4.2.
The readAsDataURL() method7.3.4.3.
The readAsText() method7.3.4.4.
The readAsArrayBuffer() method7.6.1.2.
The readAsText() method (2)7.6.1.3.
The readAsDataURL() method (2) (3)7.6.1.4.
The readAsArrayBuffer() method (2) (3)8.1.
Throwing an Exception or Returning an Error on a Blob and the synchronous flag,
run the following steps:
-
Let s be a a new body, b be the
Blobto be read from, and bytes initially set to an empty byte sequence. Set the length on s to thesizeof b. While there are still bytes to be read in b, perform the following substeps:Note: The algorithm assumes that invoking methods have checked for readability state. A
Blobin theCLOSEDstate must not have a read operation called on it.-
If the synchronous flag is set, follow the steps below:
-
Let bytes be the byte sequence that results from reading a chunk from b. If a file read error occurs reading a chunk from b, return s with the error flag set, along with a failure reason, and terminate this algorithm.
Note: Along with returning failure, the synchronous part of this algorithm must return the failure reason that occurred for throwing an exception by synchronous methods that invoke this algorithm with the synchronous flag set.
-
If there are no errors, push bytes to s, and increment s’s transmitted [Fetch] by the number of bytes in bytes. Reset bytes to the empty byte sequence and continue reading chunks as above.
-
When all the bytes of b have been read into s, return s and terminate this algorithm.
-
-
Otherwise, the synchronous flag is unset. Return s and process the rest of this algorithm asynchronously.
-
Let bytes be the byte sequence that results from reading a chunk from b. If a file read error occurs reading a chunk from b, set the error flag on s, and terminate this algorithm with a failure reason.
Note: The asynchronous part of this algorithm must signal the failure reason that occurred for asynchronous error reporting by methods expecting s and which invoke this algorithm with the synchronous flag unset.
-
If no file read error occurs, push bytes to s, and increment s’s transmitted [Fetch] by the number of bytes in bytes. Reset bytes to the empty byte sequence and continue reading chunks as above.
-
To perform an annotated task read operation#task-read-operationReferenced in:7.3.4.2.
The readAsDataURL() method7.3.4.3.
The readAsText() method7.3.4.4.
The readAsArrayBuffer() method on a Blob b,
perform the steps below:
-
Perform a read operation on b with the synchronous flag unset, along with the additional steps below.
-
If the read operation terminates with a failure reason, queue a task to process read error#process-read-errorReferenced in:7.3.4.2. The readAsDataURL() method7.3.4.3. The readAsText() method7.3.4.4. The readAsArrayBuffer() method7.3.4.5. Error Steps8.1. Throwing an Exception or Returning an Error with the failure reason and terminate this algorithm.
-
When the first chunk is being pushed to the body s during the read operation, queue a task to process read#process-readReferenced in:7.3.4.2. The readAsDataURL() method7.3.4.3. The readAsText() method7.3.4.4. The readAsArrayBuffer() method.
-
Once the body s from the read operation has at least one chunk read into it, or there are no chunks left to read from b, queue a task to process read data#process-read-dataReferenced in:7.1. The Read Operation7.3.4.2. The readAsDataURL() method7.3.4.3. The readAsText() method7.3.4.4. The readAsArrayBuffer() method. Keep queuing tasks to process read data for every chunk read or every 50ms, whichever is least frequent.
-
When all of the chunks from b are read into the body s from the read operation, queue a task to process read EOF#process-read-EOFReferenced in:7.3.4.2. The readAsDataURL() method7.3.4.3. The readAsText() method7.3.4.4. The readAsArrayBuffer() method.
Use the file reading task source for all these tasks.
7.2. The File Reading Task Source
This specification defines a new generic task source called the file reading task source#fileReadingTaskSourceReferenced in:7.1.
The Read Operation7.3.4.2.
The readAsDataURL() method7.3.4.3.
The readAsText() method7.3.4.4.
The readAsArrayBuffer() method7.3.4.6.
The abort() method,
which is used for all tasks that are queued in this specification
to read byte sequences associated with Blob and File objects.
It is to be used for features that trigger in response to asynchronously reading binary data.
7.3. The FileReader API
[Constructor#dom-filereader-filereaderReferenced in:7.3.1. Constructor, Exposed=(Window,Worker)] interface FileReader#dfn-filereaderReferenced in:1. Introduction4.2. Attributes7.3.1. Constructor (2)7.3.2. Event Handler Content Attributes7.3.3. FileReader States (2) (3) (4) (5)7.3.4. Reading a File or Blob (2) (3)7.3.4.1. The result attribute7.4. Determining Encoding7.5. Events (2)7.5.1. Event Summary7.6. Reading on Threads8.1. Throwing an Exception or Returning an Error10. Security Considerations: EventTarget { // async read methods void readAsArrayBuffer(Blob blob); void readAsText(Blob blob, optional DOMString label); void readAsDataURL(Blob blob); void abort(); // states const unsigned short EMPTY = 0; const unsigned short LOADING = 1; const unsigned short DONE = 2; readonly attribute unsigned short readyState; // File or Blob data readonly attribute (DOMString or ArrayBuffer)? result; readonly attribute DOMError? error; // event handler content attributes attribute EventHandler onloadstart; attribute EventHandler onprogress; attribute EventHandler onload; attribute EventHandler onabort; attribute EventHandler onerror; attribute EventHandler onloadend; };
7.3.1. Constructor
When the FileReader() constructor is invoked,
the user agent must return a new FileReader object.
In environments where the global object is represented by a Window or a WorkerGlobalScope object,
the FileReader constructor must be available.
7.3.2. Event Handler Content Attributes
The following are the event handler content attributes (and their corresponding event handler event types)
that user agents must support on FileReader as DOM attributes:
| event handler content attribute | event handler event type |
|---|---|
| onloadstart#dfn-onloadstartReferenced in:7.3. The FileReader API | loadstart
|
| onprogress#dfn-onprogressReferenced in:7.3. The FileReader API | progress
|
| onabort#dfn-onabortReferenced in:7.3. The FileReader API | abort
|
| onerror#dfn-onerrorReferenced in:7.3. The FileReader API | error
|
| onload#dfn-onloadReferenced in:7.3. The FileReader API | load
|
| onloadend#dfn-onloadendReferenced in:7.3. The FileReader API | loadend
|
7.3.3. FileReader States
The FileReader object can be in one of 3 states.
The readyState#dfn-readyStateReferenced in:7.3.
The FileReader API7.3.3.
FileReader States7.3.4.
Reading a File or Blob7.3.4.1.
The result attribute7.3.4.2.
The readAsDataURL() method (2) (3) (4) (5)7.3.4.3.
The readAsText() method (2) (3) (4) (5)7.3.4.4.
The readAsArrayBuffer() method (2) (3) (4) (5)7.3.4.5.
Error Steps (2) (3)7.3.4.6.
The abort() method (2) (3) (4)7.6.1.2.
The readAsText() method7.6.1.3.
The readAsDataURL() method7.6.1.4.
The readAsArrayBuffer() method attribute,
on getting,
must return the current state,
which must be one of the following values:
- EMPTY#dfn-emptyReferenced in:7.3. The FileReader API7.3.4.1. The result attribute7.3.4.6. The abort() method (numeric value 0)
- The
FileReaderobject 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 mintedFileReaderobject, until one of the read methods have been called on it. - LOADING#dfn-loadingReferenced in:7.3. The FileReader API7.3.4. Reading a File or Blob7.3.4.2. The readAsDataURL() method (2) (3) (4)7.3.4.3. The readAsText() method (2) (3) (4)7.3.4.4. The readAsArrayBuffer() method (2) (3) (4)7.3.4.5. Error Steps (2)7.3.4.6. The abort() method7.6.1.2. The readAsText() method7.6.1.3. The readAsDataURL() method7.6.1.4. The readAsArrayBuffer() method (numeric value 1)
- A
FileorBlobis being read. One of the read methods is being processed, and no error has occurred during the read. - DONE#dfn-doneReferenced in:7.3. The FileReader API7.3.3. FileReader States7.3.4.2. The readAsDataURL() method7.3.4.3. The readAsText() method7.3.4.4. The readAsArrayBuffer() method7.3.4.5. Error Steps7.3.4.6. The abort() method (2) (numeric value 2)
- The entire
FileorBlobhas been read into memory, OR a file read error occurred, OR the read was aborted usingabort(). TheFileReaderis no longer reading aFileorBlob. IfreadyStateis set toDONEit means at least one of the read methods have been called on thisFileReader.
7.3.4. Reading a File or Blob
The FileReader interface makes available three asynchronous read methods#asynchronous-read-methodsReferenced in:7.3.4.7.
Blob Parameters8.
Errors and Exceptions—readAsArrayBuffer(), readAsText(), and readAsDataURL(),
which read files into memory.
If multiple concurrent read methods are called on the same FileReader object,
user agents must throw an InvalidStateError on any of the read methods that occur
when readyState = LOADING.
(FileReaderSync makes available three synchronous read methods.
Collectively, the sync and async read methods of FileReader and FileReaderSync are referred to as just read methods#read-methodReferenced in:3.
Terminology and Algorithms7.3.3.
FileReader States (2) (3) (4)7.3.4.1.
The result attribute (2) (3) (4) (5)7.3.4.5.
Error Steps7.3.4.6.
The abort() method7.4.
Determining Encoding7.5.2.
Summary of Event Invariants (2) (3).)
7.3.4.1. The result attribute
On getting, the result#dfn-resultReferenced in:7.3.
The FileReader API7.3.4.1.
The result attribute (2) (3) (4) (5) (6) (7)7.3.4.2.
The readAsDataURL() method (2)7.3.4.3.
The readAsText() method7.3.4.4.
The readAsArrayBuffer() method7.3.4.5.
Error Steps7.3.4.6.
The abort() method (2)7.4.
Determining Encoding attribute returns a Blob's data
as a DOMString, or as an ArrayBuffer, or null,
depending on the read method that has been called on the FileReader,
and any errors that may have occurred.
The list below is normative for the result attribute
and is the conformance criteria for this attribute:
-
On getting, if the
readyStateisEMPTY(no read method has been called) then theresultattribute must returnnull. -
On getting, if an error in reading the
FileorBlobhas occurred (using any read method) then theresultattribute must returnnull. -
On getting, if the
readAsDataURL()read method is used, theresultattribute must return aDOMStringthat is a Data URL [RFC2397] encoding of theFileorBlob's data. -
On getting, if the
readAsText()read method is called and no error in reading theFileorBlobhas occurred, then theresultattribute must return a string representing theFileorBlob's data as a text string, and should decode the string into memory in the format specified by the encoding determination as aDOMString. -
On getting, if the
readAsArrayBuffer()read method is called and no error in reading theFileorBlobhas occurred, then theresultattribute must return anArrayBufferobject.
7.3.4.2. The readAsDataURL() method
When the readAsDataURL(blob)#dfn-readAsDataURLReferenced in:7.3. The FileReader API7.3.4. Reading a File or Blob7.3.4.1. The result attribute7.3.4.2. The readAsDataURL() method method is called, the user agent must run the steps below.
-
If
readyState=LOADINGthrow anInvalidStateErrorexception and terminate this algorithm. -
If the
blobis in the CLOSED readability state, set theerrorattribute of the context object to return anInvalidStateErrorexception and fire a progress event callederrorat the context object. Terminate this algorithm. -
Otherwise set
readyStatetoLOADING. -
Initiate an annotated task read operation using the
blobargument as input and handle tasks queued on the file reading task source per below. -
To process read error with a failure reason, proceed to §7.3.4.5 Error Steps.
-
To process read fire a progress event called
loadstartat the context object. -
To process read data fire a progress event called
progressat the context object. -
To process read EOF run these substeps:
-
Set
readyStatetoDONE. -
Set the
resultattribute to the body returned by the read operation as a DataURL [RFC2397]; on getting, theresultattribute returns theblobas a Data URL [RFC2397].-
Use the
blob’stypeattribute as part of the Data URL if it is available in keeping with the Data URL specification [RFC2397]. -
If the
typeattribute is not available on theblobreturn a Data URL without a media-type. [RFC2397]. Data URLs that do not have media-types [RFC2046] must be treated as plain text by conforming user agents. [RFC2397].
-
-
Fire a progress event called
loadat the context object. -
Unless
readyStateisLOADINGfire a progress event calledloadendat the context object. IfreadyStateisLOADINGdo NOT fireloadendat the context object.
-
7.3.4.3. The readAsText() method
The readAsText() method can be called with an optional parameter, label#dfn-labelReferenced in:7.3.
The FileReader API7.6.1.
The FileReaderSync API,
which is a DOMString argument that represents the label of an encoding [Encoding];
if provided, it must be used as part of the encoding determination used when processing this method call.
When the readAsText(blob, optional label)#dfn-readAsTextReferenced in:7.3. The FileReader API7.3.4. Reading a File or Blob7.3.4.1. The result attribute7.3.4.3. The readAsText() method (2)7.4. Determining Encoding method is called, the user agent must run the steps below.
-
If
readyState=LOADINGthrow anInvalidStateErrorand terminate this algorithm. -
If the
blobis in the CLOSED readability state, set theerrorattribute of the context object to return anInvalidStateErrorexception and fire a progress event callederrorat the context object. Terminate this algorithm. -
Otherwise set
readyStatetoLOADING. -
Initiate an annotated task read operation using the
blobargument as input and handle tasks queued on the file reading task source per below. -
To process read error with a failure reason, proceed to the §7.3.4.5 Error Steps.
-
To process read fire a progress event called
loadstartat the context object. -
To process read data fire a progress event called
progressat the context object. -
To process read EOF run these substeps:
-
Set
readyStatetoDONE -
Set the
resultattribute to the body returned by the read operation, represented as a string in a format determined by the encoding determination. -
Fire a progress event called
loadat the context object. -
Unless
readyStateisLOADINGfire a progress event calledloadendat the context object. IfreadyStateisLOADINGdo NOT fireloadendat the context object.
-
7.3.4.4. The readAsArrayBuffer() method
When the readAsArrayBuffer(blob)#dfn-readAsArrayBufferReferenced in:7.3. The FileReader API7.3.4. Reading a File or Blob7.3.4.1. The result attribute7.3.4.4. The readAsArrayBuffer() method method is called, the user agent must run the steps below.
-
If
readyState=LOADINGthrow anInvalidStateErrorexception and terminate this algorithm. -
If the
blobis in the CLOSED readability state, set theerrorattribute of the context object to return anInvalidStateErrorexception and fire a progress event callederrorat the context object. Terminate this algorithm. -
Otherwise set
readyStatetoLOADING. -
Initiate an annotated task read operation using the
blobargument as input and handle tasks queued on the file reading task source per below. -
To process read error with a failure reason, proceed to the §7.3.4.5 Error Steps.
-
To process read fire a progress event called
loadstartat the context object. -
To process read data fire a progress event called
progressat the context object. -
To process read EOF run these substeps:
-
Set
readyStatetoDONE -
Set the
resultattribute to the body returned by the read operation as anArrayBufferobject. -
Fire a progress event called
loadat the context object. -
Unless
readyStateisLOADINGfire a progress event calledloadendat the context object. IfreadyStateisLOADINGdo NOT fireloadendat the context object.
-
7.3.4.5. Error Steps
These error steps are to process read error with a failure reason.
-
Set the context object’s
readyStatetoDONEandresultto null if it is not already set to null. -
Set the
errorattribute on the context object; on getting, theerrorattribute must be a aDOMErrorobject that corresponds to the failure reason. Fire a progress event callederrorat the context object. -
Unless
readyStateisLOADING, fire a progress event calledloadendat the context object. IfreadyStateisLOADINGdo NOT fireloadendat the context object. -
Terminate the algorithm for any read method.
7.3.4.6. The abort() method
When the abort()#dfn-abortReferenced in:3. Terminology and Algorithms7.3. The FileReader API7.3.3. FileReader States7.5.1. Event Summary7.5.2. Summary of Event Invariants method is called, the user agent must run the steps below:
-
If
readyState=EMPTYor ifreadyState=DONEsetresulttonulland terminate this algorithm. -
If
readyState=LOADINGsetreadyStatetoDONEandresulttonull. -
If there are any tasks from the context object 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. -
Fire a progress event called
loadend.
7.3.4.7. Blob Parameters
The three asynchronous read methods,
the three synchronous read methods, URL. and createObjectURL()URL. take a createFor()Blob parameter.
This section defines this parameter.
- blob#dfn-fileBlobReferenced in:7.3. The FileReader API (2) (3)7.6.1. The FileReaderSync API (2) (3)9.5. Creating and Revoking a Blob URL (2)
- This is a
Blobargument and must be a reference to a singleFilein aFileListor aBlobargument not obtained from the underlying OS file system.
7.4. Determining Encoding
When reading Blob objects using the readAsText() read method,
the following encoding determination#encoding-determinationReferenced in:4.2.
Attributes7.3.4.1.
The result attribute7.3.4.3.
The readAsText() method (2)7.6.1.2.
The readAsText() method steps must be followed:
-
Let encoding be null.
-
If the
labelargument is present when calling the method, set encoding to the result of the getting an encoding fromlabel. -
If the getting an encoding steps above return failure, then set encoding to null.
-
If encoding is null, and the
blobargument’stypeattribute is present, and it uses a Charset Parameter [RFC2046], set encoding to the result of getting an encoding for the portion of the Charset Parameter that is a label of an encoding.Ifblobhas atypeattribute oftext/plain;charset=utf-8then 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 the getting an encoding steps above return failure, then set encoding to null.
-
If encoding is null, then set encoding to utf-8.
-
Decode this
blobusing fallback encoding encoding, and return the result. On getting, theresultattribute of theFileReaderobject returns a string in encoding format. The synchronousreadAsText()method of theFileReaderSyncobject returns a string in encoding format.
7.5. Events
The FileReader object must be the event target for all events in this specification.
When this specification says to fire a progress event#fire-a-progress-eventReferenced in:7.3.4.2.
The readAsDataURL() method (2) (3) (4) (5)7.3.4.3.
The readAsText() method (2) (3) (4) (5)7.3.4.4.
The readAsArrayBuffer() method (2) (3) (4) (5)7.3.4.5.
Error Steps (2)7.3.4.6.
The abort() method (2) called e (for some ProgressEvent e at a given FileReader reader as the context object),
the following are normative:
-
The progress event
edoes not bubble.e.bubblesmust be false [DOM] -
The progress event
eis NOT cancelable.e.cancelablemust be false [DOM]
7.5.1. Event Summary
The following are the events that are fired at FileReader objects.
7.5.2. Summary of Event Invariants
This section is informative.
The following are invariants applicable to event firing for a given asynchronous read method in this specification:
-
Once a
loadstarthas been fired, a correspondingloadendfires 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
loadevent initiates a new read -
the event handler function for a
errorevent initiates a new read.
Note: The events
loadstartandloadendare not coupled in a one-to-one manner.This example showcases "read-chaining": initiating another read from within an event handler while the "first" read continues processing.// 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
progressevent will fire whenblobhas been completely read into memory. -
No
progressevent fires after any one ofabort,load, anderrorhave fired. At most one ofabort,load, anderrorfire for a given read.
7.6. Reading on Threads
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 [[Web Workers]].
Workers can avail of both the asynchronous API (the FileReader object) and the synchronous API (the FileReaderSync object).
7.6.1. The FileReaderSync API
This interface provides methods to synchronously read#read-method-syncReferenced in:7.3.4.
Reading a File or Blob7.3.4.7.
Blob Parameters8.
Errors and Exceptions File or Blob objects into memory.
[Constructor#dom-filereadersync-filereadersyncReferenced in:7.6.1.1. Constructors, Exposed=Worker] interface FileReaderSync#dfn-FileReaderSyncReferenced in:4.2. Attributes5.2. Attributes7.3.4. Reading a File or Blob (2)7.4. Determining Encoding7.6. Reading on Threads7.6.1. The FileReaderSync API7.6.1.1. Constructors (2) { // Synchronously return strings ArrayBuffer readAsArrayBuffer(Blob blob); DOMString readAsText(Blob blob, optional DOMString label); DOMString readAsDataURL(Blob blob); };
7.6.1.1. Constructors
When the FileReaderSync() constructor is invoked,
the user agent must return a new FileReaderSync object.
In environments where the global object is represented by a WorkerGlobalScope object,
the FileReaderSync constructor must be available.
7.6.1.2. The readAsText() method
When the readAsText(blob, optional label)#dfn-readAsTextSyncReferenced in:7.4. Determining Encoding7.6.1. The FileReaderSync API7.6.1.2. The readAsText() method method is called, the following steps must be followed:
-
If
readyState=LOADINGthrow anInvalidStateErrorexception and terminate this algorithm. -
If the
blobhas been closed through theclose()method, throw anInvalidStateErrorexception and terminate this algorithm. -
Otherwise, initiate a read operation using the
blobargument, and with the synchronous flag set. If the read operation returns failure, throw the appropriate exception as defined in §8.1 Throwing an Exception or Returning an Error. Terminate this algorithm. -
If no error has occurred, return the result of the read operation represented as a string in a format determined through the encoding determination algorithm.
7.6.1.3. The readAsDataURL() method
When the readAsDataURL(blob)#dfn-readAsDataURLSyncReferenced in:7.6.1. The FileReaderSync API7.6.1.3. The readAsDataURL() method method is called, the following steps must be followed:
-
If
readyState=LOADINGthrow anInvalidStateErrorexception and terminate this algorithm. -
If the
blobhas been closed through theclose()method, throw anInvalidStateErrorexception and terminate this algorithm. -
Otherwise, initiate a read operation using the
blobargument, and with the synchronous flag set. If the read operation returns failure, throw the appropriate exception as defined in §8.1 Throwing an Exception or Returning an Error. Terminate this algorithm. -
If no error has occurred, return the result of the read operation as a Data URL [RFC2397] subject to the considerations below:
-
Use the
blob’stypeattribute as part of the Data URL if it is available in keeping with the Data URL specification [RFC2397] . -
If the
typeattribute is not available on theblobreturn a Data URL without a media-type. [RFC2397]. Data URLs that do not have media-types [RFC2046] must be treated as plain text by conforming user agents. [RFC2397].
-
7.6.1.4. The readAsArrayBuffer() method
When the readAsArrayBuffer(blob)#dfn-readAsArrayBufferSyncReferenced in:7.6.1. The FileReaderSync API7.6.1.4. The readAsArrayBuffer() method method is called, the following steps must be followed:
-
If
readyState=LOADINGthrow anInvalidStateErrorexception and terminate this algorithm. -
If the
blobhas been closed through theclose()method, throw anInvalidStateErrorexception and terminate this algorithm. -
Otherwise, initiate a read operation using the
blobargument, and with the synchronous flag set. If the read operation returns failure, throw the appropriate exception as defined in §8.1 Throwing an Exception or Returning an Error. Terminate this algorithm. -
If no error has occurred, return the result of the read operation as an
ArrayBuffer.
8. Errors and Exceptions
File read errors#file-error-readReferenced in:5.2. Attributes7.1. The Read Operation (2) (3)7.3.3. FileReader States7.5.1. Event Summary9.4.4. Sample Request and Response Headers can occur when reading files from the underlying filesystem. The list below of potential error conditions is informative.
-
The
FileorBlobbeing 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). SeeNotFoundError. -
A
FileorBlobmay be unreadable. This may be due to permission problems that occur after a reference to aFileorBlobhas been acquired (e.g. concurrent lock with another application). Additionally, the snapshot state may have changed. SeeNotReadableError. -
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 §10 Security Considerations and
SecurityError.
8.1. Throwing an Exception or Returning an Error
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 a read operation to return failure
or queue a task to process read error is called a failure reason#failureReasonReferenced in:7.1.
The Read Operation (2) (3) (4) (5) (6) (7)7.3.4.2.
The readAsDataURL() method7.3.4.3.
The readAsText() method7.3.4.4.
The readAsArrayBuffer() method7.3.4.5.
Error Steps (2)8.1.
Throwing an Exception or Returning an Error (2) (3) (4) (5) (6) (7) (8).
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#dfn-errorReferenced in:5.2.
Attributes7.3.
The FileReader API7.3.4.2.
The readAsDataURL() method7.3.4.3.
The readAsText() method7.3.4.4.
The readAsArrayBuffer() method7.3.4.5.
Error Steps (2)8.1.
Throwing an Exception or Returning an Error (2) (3) attribute of the FileReader object,
which must return a DOMError 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#exceptdef-notfounderrorReferenced in:5.2. Attributes (2)8. Errors and Exceptions8.1. Throwing an Exception or Returning an Error (2) |
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#exceptdef-securityerrorReferenced in:8. Errors and Exceptions8.1. Throwing an Exception or Returning an Error (2)10. Security Considerations (2) |
If:
For asynchronous read methods the This is a security error to be used in situations not covered by any other failure reason. |
| NotReadableError#exceptdef-notreadableerrorReferenced in:8. Errors and Exceptions8.1. Throwing an Exception or Returning an Error (2) |
If:
For asynchronous read methods the |
9. A URL for Blob and File reference
This section defines a scheme for a URL used to refer to Blob objects (and File objects).
9.1. Requirements for a New Scheme
This specification defines a scheme with URLs of the sort: blob:550e8400-e29b-41d4-a716-446655440000#aboutABBA.
This section provides some requirements and is an informative discussion.
-
This scheme should be able to be used with web APIs such as
XMLHttpRequest, and with elements that are designed to be used with HTTP URLs, such as theimgelement. In general, this scheme should be designed to be used wherever URLs can be used on the web. -
This scheme should have defined response codes, so that web applications can respond to scenarios where the resource is not found, or raises an error, etc.
-
This scheme should have an origin policy and a lifetime stipulation, to allow safe access to binary data from web applications.
URLs in this scheme should be used as a references to "in-memory"
Blobs, and also be re-used elsewhere on the platform to refer to binary resources (e.g. for video-conferencing [WebRTC]). URLs in this scheme are designed for impermanence, since they will be typically used to access "in memory" resources. -
Developers should have the ability to revoke URLs in this scheme, so that they no longer refer to
Blobobjects. This includes scenarios where file references are no longer needed by a program, but also other uses ofBlobobjects. Consider a scenario where aBlobobject can be exported from a drawing program which uses the canvas element and API [HTML]. A snapshot of the drawing can be created by exporting aBlob. This scheme can be used with theimg[HTML] element to display the snapshot; if the user deletes the snapshot, any reference to the snapshot in memory via a URL should be invalid, and hence the need to be able to revoke such a URL.
9.2. Discussion of Existing Schemes
This section is an informative discussion of existing schemes
that may have been repurposed or reused for the use cases for URLs above,
and justification for why a new scheme is considered preferable.
These schemes include HTTP [RFC7230],
file [RFC1630][RFC1738],
and a scheme such as urn:uuid [RFC4122].
One broad consideration in determining what scheme to use is providing something with intuitive appeal to web developers.
-
HTTP could be repurposed for the use cases mentioned above; it already comes with well-defined request-response semantics that are already used by web applications. But
Blobresources are typically "in-memory" resident (e.g. after a file has been read into memory), and are thus unlike "traditional" HTTP resources that are dereferenced via DNS. While some user agents automatically "proxy" the underlying file system on the local machine via an HTTP server (e.g. with URLs of the sorthttp://localhost), HTTP is not traditionally used with local resources. Moreover, an important use case for these URLs are that they can be revoked with an API call. HTTP URLs have traditionally been used for resources that may be more permanent (and that are certainly not chiefly memory-resident, such as files that a web application can read). Reusing the HTTP scheme might be confusing for web developers owing to well-established practice. -
The reuse of file URLs would involve changes to file URL use today, such as adding response codes. While they are used inconsistently in web applications, the structure of the URLs would change, and request-response behavior would have to be superimposed on what already works in a more-or-less ad-hoc manner. Modifying this for the use cases cited above is imprudent, given legacy usage. Additionally, the use cases for a Blob URL scheme call for uses beyond the file system.
-
A scheme of the sort
urn:uuid[RFC4122] could be used, though use of this scheme is unprecedented in HTML and JavaScript web applications. The urn:uuid scheme is very generic. URLs in the scheme urn:uuid have the disadvantage of unfamiliarity and inconsistency across the web platform. A new scheme has the advantage of being explicit about what is being referenced. In theory, URLs make no guarantee about what sort of resource is obtained when they are dereferenced; that is left to content labeling and media type. But in practice, the name of the scheme creates an expectation about both the resource and the protocol of the request-response transaction. Choosing a name that clarifies the primary use case—namely, access to memory-resident Blobresources—is a worthwhile compromise, and favors clarity, familiarity, and consistency across the web platform.
9.3. The Blob URL
A Blob URL#blob-urlReferenced in:4.2.
Attributes4.3.1.
The slice method9.3.
The Blob URL9.3.1.
Origin of Blob URLs9.3.3.
Discussion of Fragment Identifier9.4.
Dereferencing Model for Blob URLs (2)9.4.2.
Response Headers9.4.3.
Network Errors (2) (3)9.4.4.
Sample Request and Response Headers9.5.
Creating and Revoking a Blob URL (2) (3) (4)9.5.1.
Methods and Parameters (2) (3) (4) (5) (6) (7) (8) (9) (10)9.5.2.
Examples of Blob URL Creation and Revocation (2) (3) (4) (5) (6) (7)9.6.
Lifetime of Blob URLs (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13)10.
Security Considerations is a URL with a scheme of blob,
a host of the origin of the Blob URL,
a path with one entry comprised of a UUID [RFC4122] (see An ABNF for UUID),
and an object of the associated Blob or File.
A Blob URL may contain an optional fragment.
The Blob URL is serialized as a string according to the Unicode Serialization of a Blob URL algorithm.
A fragment, if used,
has a distinct interpretation depending on the media type of the Blob or File resource in question
(see §9.3.3 Discussion of Fragment Identifier).
blob = scheme ":" origin "/" UUID [fragIdentifier] scheme = "blob" ; scheme is always "blob" ; origin is a string representation of the Blob URL’s origin. ; UUID is as defined in [RFC4122] and An ABNF for UUID ; fragIdentifier is optional and as defined in [RFC3986] and An ABNF for Fragment Identifiers
9.3.1. Origin of Blob URLs
Blob URLs are created using URL. and/or createObjectURL()URL.,
and are revoked using createFor()URL..
The origin of a Blob URL must be the same as the effective script origin specified by the incumbent settings object at the time the method that created it—revokeObjectURL()URL. or createObjectURL()URL.—createFor()
The origin of a Blob URL, when serialized as a string, must conform to the Web Origin Specification’s Unicode Serialization of an Origin algorithm#unicode-serialization-of-an-origin-algorithmReferenced in:9.3.2. Unicode Serialization of a Blob URL (2) (3) [RFC6454]. Cross-origin requests on Blob URLs must return a network error.
Note: In practice this means that HTTP and HTTPS origins are covered by this specification as valid origins for use with Blob URLs.
This specification does not address the case of non-HTTP and non-HTTPS origins.
For instance blob:file:///Users/arunranga/702efefb-c234-4988-a73b-6104f1b615ee (which uses the "file:" origin)
may have behavior that is undefined,
even though user agents may treat such Blob URLs as valid.
9.3.2. Unicode Serialization of a Blob URL
The Unicode Serialization of a Blob URL#unicodeBlobURLReferenced in:9.3.
The Blob URL9.5.1.
Methods and Parameters (2) (3) (4) is the value returned by the following algorithm,
which is invoked by URL. and/or createObjectURL()URL.:createFor()
-
Let result be the empty string. Append the string "blob" (that is, the Unicode code point sequence U+0062, U+006C, U+006F, U+0062) to result.
-
Append the ":" (U+003A COLON) character to result.
-
Let O be the Blob URL’s origin. If the Unicode Serialization of an Origin algorithm on O returns null, user agents may substitute an implementation defined value for the return value of the Unicode Serialization of an Origin algorithm. Append the result of the Unicode Serialization of an Origin algorithm for O [RFC6454] to result.
-
Append the "/" character (U+0024 SOLIDUS) to result.
-
Generate a UUID [RFC4122] as a Unicode string and append it to result.
-
Return result.
9.3.3. Discussion of Fragment Identifier
The fragment’s resolution and processing directives depend on the media type [RFC2046] of a potentially retrieved representation,
even though such a retrieval is only performed if the Blob URL is dereferenced.
For example, in an HTML file [HTML] the fragment could be used to refer to an anchor within the file.
If the user agent does not recognize the media type of the resource,
OR if a fragment is not meaningful within the resource,
it must ignore the fragment.
The fragment must not be used to identify a resource;
only the blob scheme and the origin/path of the URL constitute a valid resource identifier.
A valid Blob URL reference could look like: blob:http://example.org:8080/550e8400-e29b-41d4-a716-446655440000#aboutABBA where "#aboutABBA" might be an HTML fragment identifier referring to an element with an id attribute of "aboutABBA".
Note: The fragment is not used to identify the resource.
Neither the URL. method
nor the createObjectURL()URL. method generate a fragment.createFor()
9.4. Dereferencing Model for Blob URLs
This section is informative.
Note: The [URL] and [Fetch] specifications should be considered normative for parsing and fetching Blob URLs.
Blob URLs are dereferenced#dereferenceReferenced in:4.2. Attributes9.3.3. Discussion of Fragment Identifier9.5.1. Methods and Parameters (2)9.5.2. Examples of Blob URL Creation and Revocation9.6. Lifetime of Blob URLs when the user agent retrieves the resource identified by the Blob URL and returns it to the requesting entity. This section provides guidance on requests and responses.
Only requests with GET [RFC7231] are supported. Specifically, responses are only a subset of the following from HTTP [RFC7231]:
9.4.1. 200 OK
This response is used if the request has succeeded, and no network errors are generated.
9.4.2. Response Headers
Along with 200 OK responses,
user agents use a Content-Type header [RFC7231] that is equal to the value of the Blob's type attribute,
if it is not the empty string.
Along with 200 OK responses,
user agents use a Content-Length header [RFC7230] that is equal to the value of the Blob's size attribute.
If a Content-Type header [RFC7231] is provided, then user agents obtain and process that media type in a manner consistent with the Mime Sniffing specification [MIMESNIFF].
If a resource identified with a Blob URL is a File object,
user agents use that file’s name attribute,
as if the response had a Content-Disposition header
with the filename parameter set to the File's name attribute [RFC6266].
Note: A corollary to this is a non-normative implementation guideline:
that the "File Save As" user interface in user agents takes into account the File's name attribute
if presenting a default name to save the file as.
9.4.3. Network Errors
Responses that do not succeed with a 200 OK act as if a network error has occurred. Network errors are used when:
-
Any request method other than GET is used.
-
The Blob URL does not have an entry in the Blob URL Store.
-
The Blob has been closed; this also results in the Blob URL not having an entry in the Blob URL Store.
-
A cross-origin request is made on a Blob URL.
-
A security error has occurred.
9.4.4. Sample Request and Response Headers
This section is informative.
This section provides sample exchanges between web applications and user agents using Blob URLs.
A request can be triggered using HTML markup of the sort <img src="blob:http://example.org:8080/550e8400-e29b-41d4-a716-446655440000">.
These examples merely illustrate the request and response;
web developers are not likely to interact with all the headers,
but the getAllResponseHeaders() method of XMLHttpRequest, if used,
will show relevant response headers.
GET http://example.org:8080/550e8400-e29b-41d4-a716-446655440000
If the Blob has an affiliated media type [RFC2046] represented by its type attribute,
then the response message should include the Content-Type header from RFC7231 [RFC7231].
See §9.4.2 Response Headers.
Example response:
200 OK Content-Type: image/jpeg Content-Length: 21897 ....
If there is a file read error associated with the Blob,
then a user agent acts as if a network error has occurred.
9.5. Creating and Revoking a Blob URL
Blob URLs are created and revoked using methods exposed on the URL object,
supported by global objects Window [HTML] and WorkerGlobalScope [[Web Workers]].
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.
partial interface URL {
static DOMString createObjectURL(Blob blob);
static DOMString createFor(Blob blob);
static void revokeObjectURL(DOMString url);
};
ECMAScript user agents of this specification must ensure
that they do not expose a prototype property on the URL interface object
unless the user agent also implements the URL [URL] specification.
In other words, URL.prototype must evaluate to true if the user agent implements the URL [URL] specification,
and must NOT evaluate to true otherwise.
9.5.1. Methods and Parameters
- The createObjectURL(blob)#dfn-createObjectURLReferenced in:7.3.4.7. Blob Parameters9.3.1. Origin of Blob URLs (2)9.3.2. Unicode Serialization of a Blob URL9.3.3. Discussion of Fragment Identifier9.5. Creating and Revoking a Blob URL9.5.1. Methods and Parameters9.5.2. Examples of Blob URL Creation and Revocation9.6. Lifetime of Blob URLs (2) static method
-
Returns a unique Blob URL.
This method must act as follows:
-
If called with a
Blobargument that has a readability state ofCLOSED, user agents must return the output of the Unicode Serialization of a Blob URL.Note: No entry is added to the Blob URL Store; consequently, when this Blob URL is dereferenced, a network error occurs.
-
Otherwise, user agents must run the following sub-steps:
-
Let url be the result of the Unicode Serialization of a Blob URL algorithm.
-
Add an entry to the Blob URL Store for url and blob.
-
Return url.
-
-
- The createFor(blob)#dfn-createForReferenced in:7.3.4.7. Blob Parameters9.3.1. Origin of Blob URLs (2)9.3.2. Unicode Serialization of a Blob URL9.3.3. Discussion of Fragment Identifier9.5. Creating and Revoking a Blob URL9.5.2. Examples of Blob URL Creation and Revocation (2) (3)9.6. Lifetime of Blob URLs (2) (3) (4) static method
-
Returns a unique Blob URL. Blob URLs created with this method are said to be auto-revoking#autoRevokingReferenced in:9.6.
Lifetime of Blob URLs since user-agents are responsible for the revocation of Blob URLs created with this method,
subject to the lifetime stipulation for Blob URLs.
This method must act as follows:
-
If called with a
Blobargument that has a readability state ofCLOSED, user agents must return the output of the Unicode Serialization of a Blob URL.Note: No entry is added to the Blob URL Store; consequently, when this Blob URL is dereferenced, a network error occurs.
-
Otherwise, user agents must run the following steps:
-
Let url be the result of the Unicode Serialization of a Blob URL.
-
Add an entry to the Blob URL Store for url and blob.
-
Add an entry to the Revocation List for url.
-
Return url.
-
In the example below, after obtaining a reference to aBlobobject (in this case, a user-selectedFilefrom the underlying file system), the static methodURL.is called on thatcreateObjectURL()Blobobject.var file = document.getElementById('file').files[0]; if(file){ blobURLref = window.URL.createObjectURL(file); myimg.src = blobURLref; .... }
-
- The revokeObjectURL(url)#dfn-revokeObjectURLReferenced in:9.3.1. Origin of Blob URLs9.5. Creating and Revoking a Blob URL9.5.1. Methods and Parameters (2)9.5.2. Examples of Blob URL Creation and Revocation (2) (3) static method
-
Revokes the Blob URL provided in the string
urlby removing the corresponding entry from the Blob URL Store. This method must act as follows:-
If the
urlrefers to aBlobthat has a readability state ofCLOSEDOR if the value provided for theurlargument is not a Blob URL, OR if the value provided for theurlargument does not have an entry in the Blob URL Store, this method call does nothing. User agents may display a message on the error console. -
Otherwise, user agents must remove the entry from the Blob URL Store for
url.Note: Subsequent attemps to dereference
urlresult in a network error, since the entry has been removed from the Blob URL Store.
The url#dfn-urlargReferenced in:9.5. Creating and Revoking a Blob URL9.5.1. Methods and Parameters (2) (3) (4) (5) (6) argument to the
revokeObjectURL()method is a Blob URL string.In the example below,window1andwindow2are separate, but in the same origin;window2could be aniframeinsidewindow1.myurl = window1.URL.createObjectURL(myblob); window2.URL.revokeObjectURL(myurl);
Since
window1andwindow2are in the same origin and share the same Blob URL Store, theURL.call ensures that subsequent dereferencing ofrevokeObjectURL()myurlresults in a the user agent acting as if a network error has occurred. -
9.5.2. Examples of Blob URL Creation and Revocation
Blob URLs are strings that are used to dereference Blob objects,
and can persist for as long as the document from which they were minted
using URL. or createObjectURL()URL.—createFor()
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()
URL.createFor(),
which allows uses such as the one above,
and obviates the need for a corresponding call by the web developer to URL.revokeObjectURL().
var blobURLref2 = URL.createFor(file); img1 = new Image(); img1.src = blobURLref2; ....
URL.createFor() to mint a Blob URL,
and appends a fragment that has an understood meaning within the resource
(in this case, it references an anchor within the HTML document).
// file is an HTML file // One of the anchor identifiers in file is "#applicationInfo" var blobURLAnchorRef = URL.createFor(file) + "#applicationInfo"; // openPopup is an utility function to open a small informational window var windowRef = openPopup(blobURLAnchorRef, "Application Info"); ....
9.6. Lifetime of Blob URLs#lifeTimeReferenced in:9.1. Requirements for a New Scheme9.5.1. Methods and Parameters9.5.2. Examples of Blob URL Creation and Revocation
A global object which exposes URL. or createObjectURL()URL. must maintain a Blob URL Store#BlobURLStoreReferenced in:4.3.2.
The close method9.4.3.
Network Errors (2)9.5.1.
Methods and Parameters (2) (3) (4) (5) (6) (7)9.6.
Lifetime of Blob URLs (2) (3) (4) (5) (6) which is a list of Blob URLs created by the createFor()URL. method
or the createObjectURL()URL. method,
and the createFor()Blob resource that each refers to.
A global object which exposes URL. must maintain a Revocation List#revokeListReferenced in:9.6.
Lifetime of Blob URLs (2) (3) (4) (5) which is a list of Blob URLs created with the createFor()URL. method.createFor()
When this specification says to add an entry to the Blob URL Store#add-an-entryReferenced in:9.5.1.
Methods and Parameters (2) for a Blob URL and a Blob input,
the user-agent must add the Blob URL and a reference to the Blob it refers to to the Blob URL Store.
When this specification says to add an entry to the Revocation List#add-an-entry-revokeReferenced in:9.5.1. Methods and Parameters for a Blob URL, user agents must add the Blob URL to the Revocation List. This is only for auto-revoking Blob URLs.
When this specification says to remove an entry from the Blob URL Store#removeTheEntryReferenced in:4.3.2.
The close method9.5.1.
Methods and Parameters9.6.
Lifetime of Blob URLs for a given Blob URL or for a given Blob,
user agents must remove the Blob URL and the Blob it refers to from the Blob URL Store.
Subsequent attempts to dereference this URL must result in a network error.
The Revocation List and the Blob URL Store must be processed together as follows:
-
Add removing the entries for all the Blob URLs in the Revocation List to the global script clean-up jobs list.
-
When all the Blob URLs in the Revocation List have had their corresponding entries in the Blob URL Store removed, remove all the Blob URLs in the Revocation List.
-
This specification adds an additional unloading document cleanup step: user agents must remove all Blob URLs from the Blob URL Store within that document.
Note: User agents are free to garbage collect resources removed from the Blob URL Store.
10. Security Considerations
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.
-
Preventing selection looping. 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 theFileListobject returned be of size 0. -
System-sensitive files (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
SecurityErrorexception for synchronous read methods, or return aSecurityErrorexception for asynchronous reads.
This section is provisional; more security data may supplement this in subsequent drafts.
11. Requirements and Use Cases
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.
A Calendar App. User’s company has a calendar. User wants to sync local events to company calendar, marked as "busy" slots (without leaking personal info). User browses for file and selects it. Thetext/calendarfile 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
downloadattribute of theaelement initiates a download, saving aFilewith the name specified. The combination of this API and thedownloadattribute onaelements allows for the creation of files within web applications, and the ability to save them locally.A Spreadsheet App. User interacts with a form, and generates some input. The form then generates a CSV (Comma Separated Variables) output for the user to import into a spreadsheet, and uses "Save...". The generated output can also be directly integrated into a web-based spreadsheet, and uploaded asynchronously. -
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.
Appendix A: Blob URL Grammar
This section uses the Augmented Backus-Naur Form (ABNF), defined in [RFC5234], to describe components of blob: URLs.
An ABNF for UUID
The following is an ABNF [RFC5234] for UUID. UUID strings must only use characters in the ranges U+002A to U+002B, U+002D to U+002E, U+0030 to U+0039, U+0041 to U+005A, U+005E to U+007E [Unicode], and should be at least 36 characters long.
UUID = time-low "-" time-mid "-"
time-high-and-version "-"
clock-seq-and-reserved
clock-seq-low "-" node
time-low = 4hexOctet
time-mid = 2hexOctet
time-high-and-version = 2hexOctet
clock-seq-and-reserved = hexOctet
clock-seq-low = hexOctet
node = 6hexOctet
hexOctet = hexDigit hexDigit
hexDigit = "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9" /
"a" / "b" / "c" / "d" / "e" / "f" /
"A" / "B" / "C" / "D" / "E" / "F"
An ABNF for Fragment Identifiers
fragIdentifier = "#" fragment
; Fragment Identifiers depend on the media type of the Blob
; fragment is defined in [RFC3986]
; fragment processing for HTML is defined in [HTML]
fragment = *( pchar / "/" / "?" )
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" /
"*" / "+" / "," / ";" / "="
Acknowledgements
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 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