Source: http://www.w3.org/TR/FileAPI/
Timestamp: 2019-04-19 23:27:50+00:00

Document:
A FileList interface, which represents an array of individually selected files from the underlying system. The user interface for selection can be invoked via <input type="file">, i.e. when the input element is in the File Upload state [HTML].
A Blob interface, which represents immutable raw binary data, and allows access to ranges of bytes within the Blob object as a separate Blob.
A URL scheme for use with binary data such as files, so that they can be referenced within web applications.
§10 Requirements and Use Cases covers the motivation behind this specification.
This API is designed to be used in conjunction with other APIs and elements on the web platform, notably: XMLHttpRequest (e.g. with an overloaded send() method for File or Blob arguments), postMessage(), DataTransfer (part of the drag and drop API defined in [HTML]) and Web Workers. Additionally, it should be possible to programmatically obtain a list of files from the input element when it is in the File Upload state [HTML]. These kinds of behaviors are defined in the appropriate affiliated specifications.
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.
When 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 abort() call.
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 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].
Each Blob must have an internal snapshot state, which must be initially set to the state of the underlying storage, if any such underlying storage exists. Further normative definition of snapshot state can be found for Files.
Set serialized.[[SnapshotState]] to value’s snapshot state.
Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
Set value’s snapshot state to serialized.[[SnapshotState]].
Set value’s underlying byte sequence to serialized.[[ByteSequence]].
If invoked with zero parameters, return a new Blob object consisting of 0 bytes, with size set to 0, and with type set to the empty string.
Let bytes be the result of processing blob parts given blobParts and options.
Let t be the type dictionary 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 ASCII lowercase.
Return a Blob object referring to bytes as its associated byte sequence, with its size set to the length of bytes, and its type set to the value of t from the substeps above.
type, the ASCII-encoded string in lower case representing the media type of the Blob. Normative conditions for this member are provided in the §3.1 Constructors.
endings, an enum which can take the values "transparent" or "native". By default this is set to "transparent". If set to "native", line endings will be converted to native in any USVString elements in blobParts.
Let bytes be an empty sequence of bytes.
If the endings member of options is "native", set s to the result of converting line endings to native of element.
Append the result of UTF-8 encoding s 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 Blob constructor may result in some data loss due to lost or scrambled character sequences.
If element is a BufferSource, get a copy of the bytes held by the buffer source, and append those bytes to bytes.
If element is a Blob, append the bytes it represents to bytes.
Note: The type of the Blob array element is ignored and will not affect type of returned Blob object.
Let native line ending be be the code point U+000A LF.
If the underlying platform’s conventions are to represent newlines as a carriage return and line feed sequence, set native line ending to the code point U+000D CR followed by the code point U+000A LF.
Set result to the empty string.
Let position be a position variable for s, initially pointing at the start of s.
Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR from s given position.
Append native line ending to result.
If position is not past the end of s and the code point at position within s equals U+000A LF advance position by 1.
Otherwise if the code point at position within s equals U+000A LF, advance position by 1 and append native line ending to result.
Examples of constructor usage follow.
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 FileReader or FileReaderSync object, or 0 if the Blob has no bytes to be read.
The ASCII-encoded string in lower case representing the media type of the Blob. On getting, user agents must return the type of a Blob as 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 type attribute can be set by the web application itself through constructor invocation and through the slice() call; in these cases, further normative conditions for this attribute are in §3.1 Constructors, §4.1 Constructor, and §3.3.1 The slice method respectively. User agents can also determine the type of a Blob, especially if the byte sequence is from an on-disk file; in this case, further normative conditions are in the file type guidelines.
Note: The type t of a Blob is considered a parsable MIME type, if performing the parse a MIME type algorithm to a byte sequence converted from the ASCII-encoded string representing the Blob object’s type does not return failure.
Note: Use of the type attribute informs the encoding determination and determines the Content-Type header when fetching blob URLs.
Let O be the Blob context object on which the slice() method is being called.
If the optional start parameter is not used as a parameter when making this call, let relativeStart be 0.
If start is negative, let relativeStart be max((size + start), 0).
Else, let relativeStart be min(start, size).
If the optional end parameter is not used as a parameter when making this call, let relativeEnd be size.
If end is negative, let relativeEnd be max((size + end), 0).
Else, let relativeEnd be min(end, size).
If the contentType parameter is not provided, let relativeContentType be set to the empty string.
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 ASCII lowercase.
Let span be max((relativeEnd - relativeStart), 0).
S refers to span consecutive bytes from O, beginning with the byte at byte-order position relativeStart.
The examples below illustrate the different types of slice() calls possible. Since the File interface inherits from the Blob interface, examples are based on the use of the File interface.
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.
User agents must return the type as 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/plain user 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.
Set serialized.[[Name]] to the value of value’s name attribute.
Set serialized.[[LastModified]] to the value of value’s lastModified attribute.
Initialize the value of value’s name attribute to serialized.[[Name]].
Initialize the value of value’s lastModified attribute to serialized.[[LastModified]].
Let bytes be the result of processing blob parts given fileBits and options.
Let n be a new string of the same size as the fileName argument to the constructor. Copy every character from fileName to 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 type member is provided and is not the empty string, let t be set to the type dictionary 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.
If the lastModified member is provided, let d be set to the lastModified dictionary 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 of Date.now() [ECMA-262]).
Note: Since ECMA-262 Date objects convert to long long values representing the number of milliseconds since the Unix Epoch, the lastModified member could be a Date object [ECMA-262].
F refers to the bytes byte sequence.
F.size is set to the number of total bytes in bytes.
F.name is set to n.
F.type is set to t.
F.lastModified is set to d.
Blob elements, which includes File elements.
A USVString parameter representing the name of the file; normative conditions for this constructor parameter can be found in §4.1 Constructor.
An optional lastModified member, which must be a long long; normative conditions for this member are provided in §4.1 Constructor.
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 File object is created using a constructor, further normative conditions for this attribute are found in §4.1 Constructor.
The last modified date of the file. On getting, if user agents can make this information available, this must return a long long set 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 a long long representing the number of milliseconds since the Unix Epoch; this is equivalent to Date.now() [ECMA-262]. If a File object is created using a constructor, further normative conditions for this attribute are found in §4.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.
In the examples below, metadata from a file object is displayed meaningfully, and a file object is created with a name and a last modified date.
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.
Set serialized.[[Files]] to an empty list.
For each file in value, append the sub-serialization of file to serialized.[[Files]].
For each file of serialized.[[Files]], add the sub-deserialization of file to value.
index must be treated by user agents as value for the position of a File object in the FileList, with 0 representing the first file. Supported property indices are the numbers in the range zero to one less than the number of File objects represented by the FileList object. If there are no such File objects, 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.
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 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.
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.
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 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.
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. 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.
Use the file reading task source for all these tasks.
This specification defines a new generic task source called the file reading task source, 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.
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. 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.
On getting, the result 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.
On getting, if an error in reading the File or Blob has occurred (using any read method) then the result attribute must return null.
On getting, if the readAsDataURL() read method is used, the result attribute must return a DOMString that is a Data URL [RFC2397] encoding of the File or Blob's data.
On getting, if the readAsBinaryString() read method is called and no error in reading the File or Blob has occurred, then the result attribute must return a DOMString representing the File or Blob's data as a binary string, in which every byte is represented by a code unit of equal value [0...255].
On getting, if the readAsText() read method is called and no error in reading the File or Blob has occurred, then the result attribute must return a string representing the File or Blob's data as a text string, and should decode the string into memory in the format specified by the encoding determination as a DOMString.
On getting, if the readAsArrayBuffer() read method is called and no error in reading the File or Blob has occurred, then the result attribute must return an ArrayBuffer object.
When the readAsDataURL(blob) method is called, the user agent must run the steps below.
If readyState = LOADING throw an InvalidStateError exception and terminate this algorithm.
Otherwise set readyState to LOADING.
Initiate an annotated task read operation using the blob argument as input and handle tasks queued on the file reading task source per below.
To process read error with a failure reason, proceed to §6.3.4.6 Error Steps.
To process read fire a progress event called loadstart at the context object.
To process read data fire a progress event called progress at the context object.
Set the result attribute to the body returned by the read operation as a DataURL [RFC2397]; on getting, the result attribute returns the blob as a Data URL [RFC2397].
Use the blob’s type attribute as part of the Data URL if it is available in keeping with the Data URL specification [RFC2397].
If the type attribute is not available on the blob return 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 load at the context object.
Unless readyState is LOADING fire a progress event called loadend at the context object. If readyState is LOADING do NOT fire loadend at the context object.
The readAsText() method can be called with an optional parameter, encoding, 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, encoding) method is called, the user agent must run the steps below.
If readyState = LOADING throw an InvalidStateError and terminate this algorithm.
To process read error with a failure reason, proceed to the §6.3.4.6 Error Steps.
Set the result attribute to the body returned by the read operation, represented as a string in a format determined by the encoding determination.
When the readAsArrayBuffer(blob) method is called, the user agent must run the steps below.
Set the result attribute to the body returned by the read operation as an ArrayBuffer object.
When the readAsBinaryString(blob) method is called, the user agent must run the steps below.
Set the result attribute to the body returned by the read operation as a binary string.
The use of readAsArrayBuffer() is preferred over readAsBinaryString(), which is provided for backwards compatibility.
These error steps are to process read error with a failure reason.
Set the context object’s readyState to DONE and result to null if it is not already set to null.
Set the error attribute on the context object; on getting, the error attribute must be a a DOMException object that corresponds to the failure reason. Fire a progress event called error at the context object.
Unless readyState is LOADING, fire a progress event called loadend at the context object. If readyState is LOADING do NOT fire loadend at the context object.
Terminate the algorithm for any read method.
If readyState = EMPTY or if readyState = DONE set result to null and terminate this algorithm.
If readyState = LOADING set readyState to DONE and result to null.
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.
The asynchronous read methods, the synchronous read methods, and URL.createObjectURL() take a Blob parameter. This section defines this parameter.
This is a Blob argument and must be a reference to a single File in a FileList or a Blob argument not obtained from the underlying OS file system.
If the encoding argument is present when calling the method, set encoding to the result of the getting an encoding from encoding.
If the getting an encoding steps above return failure, then set encoding to null.
If encoding is null, and the blob argument’s type attribute 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.
If 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 null, then set encoding to utf-8.
Decode this blob using fallback encoding encoding, and return the result. On getting, the result attribute of the FileReader object returns a string in encoding format. The synchronous readAsText() method of the FileReaderSync object returns a string in encoding format.
The FileReader object must be the event target for all events in this specification.
The following are the events that are fired at FileReader objects.
error ProgressEvent When the read has failed (see file read errors).
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.
This example showcases "read-chaining": initiating another read from within an event handler while the "first" read continues processing.
One progress event will fire when blob has been completely read into memory.
No progress event fires before loadstart.
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.
No abort, load, or error event fires after loadend.
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).
This interface provides methods to synchronously read File or Blob objects into memory.
Initiate a read operation using the blob argument, and with the synchronous flag set. If the read operation returns failure, throw the appropriate exception as defined in §7.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.
If no error has occurred, return the result of the read operation as an ArrayBuffer.
If no error has occurred, return the result of the read operation as an binary string.
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.
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.
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.
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 error attribute must return a NotFoundError exception and synchronous read methods must throw a NotFoundError exception.
it is determined that certain files are unsafe for access within a Web application, this is the UnsafeFile failure reason.
it is determined that too many read calls are being made on File or Blob resources, this is the TooManyReads failure reason.
For asynchronous read methods the error attribute may return a SecurityError exception and synchronous read methods may throw a SecurityError exception.
This is a security error to be used in situations not covered by any other failure reason.
the snapshot state of a File or a Blob does not match the state of the underlying storage, this is the SnapshotState failure reason.
the File or Blob cannot be read, typically due due to permission problems that occur after a snapshot state has been established (e.g. concurrent lock on the underlying storage with another application) then this is the FileLock failure reason.
For asynchronous read methods the error attribute must return a NotReadableError exception and synchronous read methods must throw a NotReadableError exception.
This section defines a scheme for a URL used to refer to Blob objects (and File objects).
Note: other specifications, such as [MEDIA-SOURCE] extend this scheme to also refer to other types of objects.
Blob (or object) URLs are URLs like blob:http://example.com/550e8400-e29b-41d4-a716-446655440000. This enables integration of Blobs and Files with other Web Platform 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(blob) 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 (typically a Blob, but other specs can extend this to refer to other types of objects), and an environment (an environment settings 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.
Append the string "blob:" to result.
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 U+0024 SOLIDUS (/) to result.
Generate a UUID [RFC4122] as a string and append it to result.
An example of a blob URL that can be generated by this algorithm is blob:https://example.org/9115d58c-bcda-ff47-86e5-083e9a2153041.
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.
Let url string be the result of serializing url.
Assert: url’s scheme is "blob".
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 an fetching model for blob URLs are defined in the [URL] and [Fetch] specifications.
Let entry be the result of resolving url.
If entry is not failure, return entry’s environment's origin.
Let nested url be the result of parsing url’s path.
Return a new opaque origin, if nested url is failure, and nested url’s origin otherwise.
Note: The effect of this algorithm is that 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. 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.
The [URL] spec should be updated to refer to this algorithm to resolve the origin of a blob URL when the URL is first parsed. This is tracked in issue #63 and in whatwg/url#127.
Let environment be the Document's relevant settings object.
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.
The createObjectURL(blob) static method must return the result of adding an entry to the blob URL store for blob.
Let url record be the result of parsing url.
If url record’s scheme is not "blob", return.
Let origin be the result of resolving the origin of url record.
Let settings be the current settings object.
If origin is not same origin with settings’s origin, return.
Remove an entry from the Blob URL Store for url.
Note: This means that rather than throwing some kind of error, attempting to revoke a URL that isn’t registered 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.
In the example below, window1 and window2 are separate, but in the same origin; window2 could be an iframe inside window1.
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.revokeObjectURL() call ensures that subsequent dereferencing of 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.createObjectURL()—see §8.2.3 Lifetime of blob URLs.
This section gives sample usage of creation and revocation of blob URLs with explanations.
In the example below, URL.revokeObjectURL() is explicitly called.
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 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.
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 SecurityError exception for synchronous read methods, or return a SecurityError exception for asynchronous reads.
A lyrics viewer. User wants to read song lyrics from songs in his plist file. User browses for plist file. File is opened, read, parsed, and presented to the user as a sortable, actionable list within a web application. User can select songs to fetch lyrics. User uses the "browse for file" dialog.
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. The 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.
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.
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.
A Video/Photo Upload App. User is able to select large files for upload, which can then be "chunk-transfered" to the server.
Thanks to Robin Berjon, Jonas Sicking and Vsevolod Shmyroff for editing the original specification.

References: §10
 §3
 §3
 §4
 §3
 §4
 §4
 §4
 §4
 §6
 §6
 §7
 §9
 §8