file api

51
File API W3C Working Draft 21 April 2015 This version: http://www.w3.org/TR/2015/WDFileAPI20150421/ Latest published version: http://www.w3.org/TR/FileAPI/ Latest editor's draft: https://w3c.github.io/FileAPI/ Test suite: http://w3ctest.org/FileAPI/ Previous version: http://www.w3.org/TR/2013/WDFileAPI20130912/ Editors: Arun Ranganathan , Mozilla Corporation, <[email protected]> Jonas Sicking, Mozilla Corporation <[email protected]> Repository and Participation: We are on github. File a bug/issue. Commit history. Mailing list search. Copyright © 2015 W3C ® (MIT , ERCIM , Keio , Beihang ). W3C liability , trademark and document use rules apply. Abstract This specification provides an API for representing file objects in web applications, as well as programmatically selecting them and accessing their data. This includes: 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 File interface, which includes readonly informational attributes about a file

Upload: rithuik-yerrabrolu

Post on 12-Jan-2016

3 views

Category:

Documents


0 download

DESCRIPTION

file

TRANSCRIPT

Page 1: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 1/51

File APIW3C Working Draft 21 April 2015

This version:http://www.w3.org/TR/2015/WD­FileAPI­20150421/

Latest published version:http://www.w3.org/TR/FileAPI/

Latest editor's draft:https://w3c.github.io/FileAPI/

Test suite:http://w3c­test.org/FileAPI/

Previous version:http://www.w3.org/TR/2013/WD­FileAPI­20130912/

Editors:Arun Ranganathan, Mozilla Corporation, <[email protected]>Jonas Sicking, Mozilla Corporation <[email protected]>

Repository and Participation:We are on github.File a bug/issue.Commit history.Mailing list search.

Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and document userules apply.

Abstract

This specification provides an API for representing file objects in web applications,as well as programmatically selecting them and accessing their data. Thisincludes:

A FileList interface, which represents an array of individually selected filesfrom the underlying system. The user interface for selection can be invokedvia <input type="file">, i.e. when the input element is in the File Uploadstate [HTML] .

A Blob interface, which represents immutable raw binary data, and allowsaccess to ranges of bytes within the Blob object as a separate Blob.

A File interface, which includes readonly informational attributes about a file

Page 2: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 2/51

such as its name and the date of the last modification (on disk) of the file.

A FileReader interface, which provides methods to read a File or a Blob, andan event model to obtain the results of these reads.

A URL scheme for use with binary data such as files, so that they can bereferenced within web applications.

Additionally, this specification defines objects to be used within threaded webapplications for the synchronous reading of files.

The section on Requirements and Use Cases [REQ] covers the motivation behindthis specification.

This API is designed to be used in conjunction with other APIs and elements onthe web platform, notably: XMLHttpRequest (e.g. with an overloaded send()method for File or Blob arguments), postMessage, DataTransfer (part of the dragand drop API defined in [HTML]) and Web Workers. Additionally, it should bepossible to programmatically obtain a list of files from the input element when it isin the File Upload state[HTML]. These kinds of behaviors are defined in theappropriate affiliated specifications.

Status of this Document

This section describes the status of this document at the time of its publication.Other documents may supersede this document. A list of current W3C publicationsand the latest revision of this technical report can be found in the W3C technicalreports index at http://www.w3.org/TR/.

If you have comments for this spec, please send them to public­[email protected] a Subject: prefix of [FileAPI]. See Bugzilla for this specification's open bugs.

This document was published by the Web Applications Working Group as aWorking Draft. This document is intended to become a W3C Recommendation. Ifyou wish to make comments regarding this document, please send them to public­[email protected] (subscribe, archives). All comments are welcome.

Publication as a Working Draft does not imply endorsement by the W3CMembership. This is a draft document and may be updated, replaced or obsoletedby other documents at any time. It is inappropriate to cite this document as otherthan work in progress.

This document was produced by a group operating under the 5 February 2004W3C Patent Policy. W3C maintains a public list of any patent disclosures made inconnection with the deliverables of the group; that page also includes instructionsfor disclosing a patent. An individual who has actual knowledge of a patent whichthe individual believes contains Essential Claim(s) must disclose the information inaccordance with section 6 of the W3C Patent Policy.

This document is governed by the 1 August 2014 W3C Process Document.

Page 3: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 3/51

Table of Contents

1. Introduction2. Conformance3. Dependencies4. Terminology5. The Blob Interface and Binary Data

5.1. Constructors5.1.1. Constructor Parameters

5.2. Attributes5.3. Methods and Parameters

5.3.1. The slice method5.3.2. The close method

6. The File Interface6.1 File Constructor6.2. Attributes

7. The FileList Interface7.1. Attributes7.2. Methods and Parameters

8. Reading Data8.1 The Read Operation8.2. The File Reading Task Source8.3. FileReader

8.3.1. Constructors8.3.2. Event Handler Attributes8.3.3. FileReader States8.3.4. Reading a File or Blob

8.3.4.1. The result attribute8.3.4.2. The readAsDataURL(blob) method8.3.4.3. The readAsText(blob, label) method8.3.4.4. The readAsArrayBuffer(blob) method8.3.4.5. Error Steps8.3.4.6. The abort() method

8.4. Determining Encoding8.5. Events

8.5.1. Event Summary8.5.2. Summary of Event Invariants

8.6. Reading on Threads8.6.1. The FileReaderSync Interface

8.6.1.1. Constructors8.6.1.2. The readAsText method8.6.1.3. The readAsDataURL method8.6.1.4. The readAsArrayBuffer method

9. Errors and Exceptions9.1. Throwing an Exception or Returning an Error

Page 4: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 4/51

10. A URL for Blob and File reference10.1. Requirements for a New Scheme10.2. Discussion of Existing Schemes10.3. Definition of blob URL Scheme

10.3.1. Origin of Blob URLs10.3.2. Unicode Serialization of a Blob URL10.3.3. Discussion of Fragment Identifier

10.4. Dereferencing Model for Blob URLs10.4.1. 200 OK10.4.2 Processing Media Types10.4.3. NetworkError Conditions10.4.4. Examples

10.5. Creating and Revoking a Blob URL10.5.1. Methods and Parameters10.5.2. Examples of Blob URL Creation and Revocation

10.6. Lifetime of Blob URLs

11. Security Considerations12. Requirements and Use Cases13. Appendix A14. Acknowledgements15. References

15.1. Normative references15.2. Informative References

1. Introduction

This section is informative.

Web applications should have the ability to manipulate as wide as possible arange of user input, including files that a user may wish to upload to a remoteserver or manipulate inside a rich web application. This specification defines thebasic representations for files, lists of files, errors raised by access to files, andprogrammatic ways to read files. Additionally, this specification also defines aninterface that represents "raw data" which can be asynchronously processed onthe main thread of conforming user agents. The interfaces and API defined in thisspecification can be used with other interfaces and APIs exposed to the webplatform.

The File interface represents file data typically obtained from the underlying (OS)file system, and the Blob interface ("Binary Large Object" ­ a name originallyintroduced to web APIs in Google Gears) represents immutable raw data. File orBlob reads should happen asynchronously on the main thread, with an optionalsynchronous API used within threaded web applications. An asynchronous API forreading 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 readand access a File or Blob's data. A FileReader object provides asynchronous readmethods to access that file's data through event handler attributes and the firing of

Page 5: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 5/51

events. The use of events and event handlers allows separate code blocks theability to monitor the progress of the read (which is particularly useful for remotedrives or mounted drives, where file access performance may vary from localdrives) and error conditions that may arise during reading of a file. An example willbe illustrative.

Example

In the example below, different code blocks handle progress, error,and success conditions.

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

ECMAScript

Page 6: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 6/51

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 sectionsmarked 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 Keywords for use in RFCs to Indicate Requirement Levels [RFC2119].

The following conformance classes are defined by this specification:

conforming user agentA user agent is considered to be a conforming user agent if it satisfies all ofthe MUST­, REQUIRED­ and SHALL­level criteria in this specification that apply toimplementations. This specification uses both the terms "conforming useragent" and "user agent" to refer to this product class.

User agents may implement algorithms in this specifications in any waydesired, so long as the end result is indistinguishable from the result thatwould be obtained from the specification's algorithms.

User agents that use ECMAScript to implement the APIs defined in thisspecification must implement them in a manner consistent with the ECMAScriptBindings defined in the Web IDL specification [WEBIDL] as this specification usesthat specification and terminology.

3. Dependencies

This specification relies on underlying specifications.

DOMA conforming user agent must support at least the subset of the functionalitydefined in DOM4 that this specification relies upon; in particular, it mustsupport EventTarget. [DOM4]

Progress Events

Page 7: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 7/51

A conforming user agent must support the Progress Events specification.Data access on read operations is enabled via Progress Events.[ProgressEvents]

HTMLA conforming user agent must support at least the subset of the functionalitydefined in HTML that this specification relies upon; in particular, it mustsupport event loops and event handler attributes. [HTML]

Web IDLA conforming user agent must also be a conforming implementation of theIDL fragments in this specification, as described in the Web IDL specification.[WebIDL]

Typed ArraysA conforming user agent must support the Typed Arrays specification[TypedArrays].

Parts of this specification rely on the Web Workers specification; for those parts ofthis specification, the Web Workers specification is a normative dependency.[Workers]

4. Terminology

4.1 Terms

The terms and algorithms document, unloading document cleanup steps,event handler attributes, event handler event type, effective script origin,incumbent settings object, event loops, task, task source, URL, global scriptcleanup jobs list, global script cleanup, queue a task, UTF­8, UTF­16.structured clone, collect a sequence of characters and converting a string toASCII lowercase are as defined by the HTML specification [HTML].

The terms origin and same origin are as defined by the Web Origin Conceptspecification [ORIGIN].

When this specification says to terminate an algorithm the user agent mustterminate the algorithm after finishing the step it is on, and return from it.Asynchronous read methods defined in this specification may return before thealgorithm in question is terminated, and can be terminated by an abort() call.

The term throw in this specification, as it pertains to exceptions, is used as definedin the DOM4 specification [DOM4].

The term byte in this specification is used as defined in the Encoding Specification[Encoding Specification].

The term chunk in this specification is used as defined in the StreamsSpecification [Streams Specification.]

Page 8: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 8/51

The term context object in this specification is used as defined in the DOM4specification [DOM4].

The terms URL, relative URL, base URL, URL parser, basic URL Parser,scheme, host, relative scheme, scheme data, and fragment are as defined bythe WHATWG URL Specification [URL].

The terms request, response, body and cross­origin request are as defined inthe WHATWG Fetch Specification [Fetch Specification].

The term Unix Epoch is used in this specification to refer to the time 00:00:00UTC on January 1 1970 (or 1970­01­01T00:00:00Z ISO 8601); this is the sametime that is conceptually "0" in ECMA­262 [ECMA­262].

The algorithms and steps in this specification use the following mathematicaloperations:

max(a,b) returns the maximum of a and b, and is always performed onintegers as they are defined in WebIDL [WebIDL]; in the case of max(6,4) theresult 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 onintegers as they are defined in WebIDL [WebIDL]; in the case of min(6,4) theresult 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].

5. The Blob Interface and Binary Data

A Blob object refers to a byte sequence, and has a size attribute which is the totalnumber 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, which is one of OPENED or CLOSED. A Blob thatrefers to a byte sequence, including one of 0 bytes, is said to be in the OPENEDreadability state. A Blob is said to be closed if its close method has been called. ABlob that is closed is said to be in the CLOSED readability state.

Each Blob must have an internal snapshot state, which must be initially set to thestate of the underlying storage, if any such underlying storage exists, and must bepreserved through structured clone. Further normative definition of snapshot statecan be found for files.

[Constructor, Constructor(sequence<(ArrayBuffer or ArrayBufferView or Blob or DOMString)> interface Blob readonly attribute unsigned long long size;

IDL

Page 9: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 9/51

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 DOMString type = ""; ;

5.1. Constructors

The Blob() constructor can be invoked with zero or more parameters. When theBlob() constructor is invoked, user agents must run the following Blobconstructor steps:

1. If invoked with zero parameters, return a new Blob object with its readabilitystate set to OPENED, consisting of 0 bytes, with size set to 0, and with type setto the empty string.

2. Otherwise, the constructor is invoked with a blobParts sequence. Let a bethat sequence.

3. Let bytes be an empty sequence of bytes.

4. Let length be a's length. For 0 ≤ i < length, repeat the following steps:

1. Let element be the ith element of a.

2. If element is a DOMString, run the following substeps:

1. Let s be the result of converting element to a sequence ofUnicode characters [Unicode] using the algorithm for doing so inWebIDL [WebIDL].

2. Encode s as UTF­8 and append the resulting bytes to bytes.

Note

The algorithm from WebIDL [WebIDL] replacesunmatched surrogates in an invalid UTF­16 string with

Page 10: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 10/51

U+FFFD replacement characters. Scenarios exist whenthe Blob constructor may result in some data loss due tolost or scrambled character sequences.

3. If element is an ArrayBufferView [TypedArrays], convert it to asequence of byteLength bytes from the underlying ArrayBuffer, startingat the byteOffset of the ArrayBufferView [TypedArrays], and appendthose bytes to bytes.

4. If element is an ArrayBuffer [TypedArrays], convert it to a sequence ofbyteLength bytes, and append those bytes to bytes.

5. If element is a Blob, append the bytes it represents to bytes. The typeof the Blob array element is ignored.

5. If the type member of the optional options argument is provided and is notthe empty string, run the following sub­steps:

1. Let t be the type dictionary member. If t contains any charactersoutside the range U+0020 to U+007E, then set t to the empty string andreturn from these substeps.

2. Convert every character in t to lowercase using the "converting a stringto ASCII lowercase" algorithm [WebIDL].

6. Return a Blob object with its readability state set to OPENED, referring to bytesas its associated byte sequence, with its size set to the length of bytes, andits type set to the value of t from the substeps above.

Note

The type t of a Blob is considered a parsable MIME type if theASCII­encoded string representing the Blob object's type, whenconverted to a byte sequence, does not return undefined for theparse MIME type algorithm [MIMESNIFF].

5.1.1. Constructor Parameters

The Blob() constructor can be invoked with the parameters below:

A blobParts sequencewhich takes any number of the following types of elements, and in any order:

ArrayBuffer [TypedArrays] elements.

ArrayBufferView [TypedArrays] elements.

Blob elements.

Page 11: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 11/51

DOMString [WebIDL] elements.

An optional BlobPropertyBagwhich takes one member:

type, the ASCII­encoded string in lower case representing the mediatype of the Blob. Normative conditions for this member are provided inthe Blob constructor steps.

Example

Examples of constructor usage follow.

// 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]);

5.2. Attributes

sizeReturns the size of the byte sequence in number of bytes. On getting,conforming user agents must return the total number of bytes that can beread by a FileReader or FileReaderSync object, or 0 if the Blob has no bytesto be read. If the Blob has a readability state of CLOSED then size must return0.

typeThe ASCII­encoded string in lower case representing the media type of the

ECMAScript

Page 12: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 12/51

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 bytesequence, it is a parsable MIME type [MIMESNIFF], or the empty string ­­ 0bytes ­­ if the type cannot be determined. The type attribute can be set by theweb application itself through constructor invocation and through the slicecall; in these cases, further normative conditions for this attribute are in theBlob constructor steps, the File Constructor steps, and the slice methodalgorithm 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, furthernormative conditions are in the file type guidelines..

isClosedThe boolean value that indicates whether the Blob is in the CLOSED readabilitystate. On getting, user agents must return false if the Blob is in the OPENEDreadability state, and true if the Blob is in the CLOSED readability state as aresult of the close method being called.

Note

Use of the type attribute informs the encoding determination andparsing the Content­Type header when dereferencing Blob URLs.

5.3. Methods and Parameters

5.3.1. The slice method

The slice method returns a new Blob object with bytes ranging from the optionalstart parameter upto but not including the optional end parameter, and with a typeattribute that is the value of the optional contentType parameter. It must act asfollows :

1. Let O be the Blob context object on which the slice method is being called.

2. The optional start parameter is a value for the start point of a slice call, andmust be treated as a byte­order position, with the zeroth positionrepresenting the first byte. User agents must process slice with startnormalized according to the following:

a. If the optional start parameter is not used as a parameter whenmaking this call, let relativeStart be 0.

b. If start is negative, let relativeStart be max((size + start), 0).

c. Else, let relativeStart be min(start, size).

3. The optional end parameter is a value for the end point of a slice call. Useragents must process slice with end normalized according to the following:

a. If the optional end parameter is not used as a parameter when making

Page 13: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 13/51

this call, let relativeEnd be size.

b. If end is negative, let relativeEnd be max((size + end), 0)

c. Else, let relativeEnd be min(end, size)

4. The optional contentType parameter is used to set the ASCII­encoded stringin lower case representing the media type of the Blob. User agents mustprocess the slice with contentType normalized according to the following:

A. If the contentType parameter is not provided, let relativeContentType beset to the empty string .

B. Else let relativeContentType be set to contentType and run thesubsteps below:

1. If relativeContentType contains any characters outside the rangeof U+0020 to U+007E, then set relativeContentType to the emptystring and return from these substeps.

2. Convert every character in relativeContentType to lower caseusing the "Converting a string to ASCII lowercase" algorithm.

5. Let span be max((relativeEnd ­ relativeStart), 0).

6. Return a new Blob object S with the following characteristics:

a. S has a readability state equal to that of O's readability state.

Note

The readability state of the context object is retained bythe Blob object returned by the slice call; this hasimplications on whether the returned Blob is actuallyusable for read operations or as a Blob URL.

b. S refers to span consecutive bytes from O, beginning with the byte atbyte­order position relativeStart.

c. S.size = span.

d. S.type = relativeContentType.

Note

The type t of a Blob is considered a parsable MIME type ifthe ASCII­encoded string representing the Blob object'stype, when converted to a byte sequence, does not returnundefined for the parse MIME type algorithm[MIMESNIFF].

Page 14: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 14/51

Example

The examples below illustrate the different types of slice callspossible. 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");

5.3.2. The close method

The close method is said to close a Blob, and must act as follows on the Blob onwhich the method has been called:

1. If the readability state of the context object is CLOSED, terminate this algorithm.

2. Otherwise, set the readability state of the context object to CLOSED.

3. If the context object has an entry in the Blob URL Store, remove the entrythat corresponds to the context object.

6. The File Interface

ECMAScript

Page 15: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 15/51

A File object is a Blob object with a name attribute, which is a string; it can becreated within the web application via a constructor, or is a reference to a bytesequence 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 theFile object is created.

Note

This is a non­trivial requirement to implement for user agents, and isthus not a must but a should [RFC2119]. User agents shouldendeavor to have a File object's snapshot state set to the state ofthe underlying storage on disk at the time the reference is taken. Ifthe file is modified on disk following the time a reference has beentaken, the File's snapshot state will differ from the state of theunderlying storage. User agents may use modification time stampsand other mechanisms to maintain snapshot state, but this is left asan implementation detail.

When a File object refers to a file on disk, user agents must return the type of thatfile, and must follow the file type guidelines below:

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 aparsable MIME type [MIMESNIFF], or the empty string ­­ 0 bytes ­­ if the typecannot be determined.

When the file is of type text/plain user agents must NOT append a charsetparameter to the dictionary of parameters portion of the media type[MIMESNIFF].

User agents must not attempt heuristic determination of encoding, includingstatistical methods.

[Constructor(sequence<(Blob or DOMString or ArrayBufferView or ArrayBuffer)> [EnsureUTF16] DOMString fileName, optional FilePropertyBag options), Exposed=Window,Worker]interface File : Blob

readonly attribute DOMString name; readonly attribute long long lastModified;

;

dictionary FilePropertyBag DOMString type = ""; long long lastModified;

IDL

Page 16: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 16/51

;

6.1 Constructor

The File constructor is invoked with two or three parameters, depending onwhether the optional dictionary parameter is used. When the File() constructor isinvoked, user agents must run the following File constructor steps:

1. Let a be the fileBits sequence argument. Let bytes be an empty sequenceof bytes. Let length be a's length. For 0 ≤ i < length, repeat the followingsteps:

1. Let element be the i'th element of a.

2. If element is a DOMString, run the following substeps:

1. Let s be the result of converting element to a sequence ofUnicode characters [Unicode] using the algorithm for doing so inWebIDL [WebIDL].

2. Encode s as UTF­8 and append the resulting bytes to bytes.

Note

The algorithm from WebIDL [WebIDL] replacesunmatched surrogates in an invalid UTF­16 string withU+FFFD replacement characters. Scenarios exist whenthe Blob constructor may result in some data loss due tolost or scrambled character sequences.

3. If element is an ArrayBufferView [TypedArrays], convert it to asequence of byteLength bytes from the underlying ArrayBuffer, startingat the byteOffset of the ArrayBufferView [TypedArrays], and appendthose bytes to bytes.

4. If element is an ArrayBuffer [TypedArrays], convert it to a sequence ofbyteLength bytes, and append those bytes to bytes.

5. If element is a Blob, append the bytes it represents to bytes. The typeof the Blob argument must be ignored.

2. Let n be a new string of the same size as the fileName argument to theconstructor. Copy every character from fileName to n, replacing any "/"character (U+002F SOLIDUS) with a ":" (U+003A COLON).

Note

Page 17: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 17/51

Underlying OS filesystems use differing conventions for filename; with constructed files, mandating UTF­16 lessensambiquity when file names are converted to byte sequences.

3. If the optional FilePropertyBag dictionary argument is used, then run thefollowing substeps:

1. If the type member is provided and is not the empty string, let t be setto the type dictionary member. If t contains any characters outside therange U+0020 to U+007E, then set t to the empty string and return fromthese substeps.

2. Convert every character in t to lowercase using the "converting a stringto ASCII lowercase algorithm" [WebIDL].

3. If the lastModified member is provided, let d be set to the lastModifieddictionary member. If it is not provided, set d to the current date andtime 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 longvalues representing the number of milliseconds since theUnix Epoch, the lastModified member could be a Dateobject [ECMA­262].

4. Return a new File object F such that:

1. F has a readability state of OPENED.

2. F refers to the bytes byte sequence.

3. F.size is set to the number of total bytes in bytes.

4. F.name is set to n.

5. F.type is set to t.

Note

The type t of a File is considered a parsable MIME type ifthe ASCII­encoded string representing the File object'stype, when converted to a byte sequence, does not returnundefined for the parse MIME type algorithm[MIMESNIFF].

6. F.lastModified is set to d.

6.1.1 Constructor Parameters

Page 18: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 18/51

The File() constructor can be invoked with the parameters below:

A fileBits sequencewhich takes any number of the following elements, and in any order:

ArrayBuffer [TypedArrays] elements.

ArrayBufferView [TypedArrays] elements.

Blob elements, which includes File elements.

DOMString [WebIDL] elements.

A name parameterA DOMString [WebIDL] parameter representing the name of the file; normativeconditions for this constructor parameter can be found in the File constructorsteps.

An optional FilePropertyBag dictionarywhich takes the following members:

An optional type member; the ASCII­encoded string in lower caserepresenting the media type of the File. Normative conditions for thismember are provided in the File constructor steps.

An optional lastModified member, which must be a long long;normative conditions for this member are provided in the Fileconstructor steps.

6.2. Attributes

nameThe name of the file; on getting, this must return the name of the file as astring. There are numerous file name variations and conventions used bydifferent underlying OS file systems; this is merely the name of the file,without path information. On getting, if user agents cannot make thisinformation available, they must return the empty string. If a File object iscreated using a constructor, further normative conditions for this attribute arefound in the file constructor steps.

lastModifiedThe last modified date of the file. On getting, if user agents can make thisinformation available, this must return a long long set to the time the file waslast modified as the number of milliseconds since the Unix Epoch. If the lastmodification date and time are not known, the attribute must return thecurrent date and time as a long long representing the number ofmilliseconds since the Unix Epoch; this is equivalent to Date.now() [ECMA­262]. If a File object is created using a constructor, further normativeconditions for this attribute are found in the file constructor steps.

The File interface is available on objects that expose an attribute of type FileList;

Page 19: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 19/51

these objects are defined in HTML [HTML]. The File interface, which inherits fromBlob, is immutable, and thus represents file data that can be read into memory atthe time a read operation is initiated. User agents must process reads on files thatno longer exist at the time of read as errors, throwing a NotFoundError exception ifusing a FileReaderSync on a Web Worker [Workers] or firing an error event withthe error attribute returning a NotFoundError DOMError.

Example

In the examples below, metadata from a file object is displayedmeaningfully, and a file object is created with a name and a lastmodified date.

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)

...

7. The FileList Interface

The FileList interface should be considered "at risk" since thegeneral trend on the Web Platform is to replace such interfaces withthe Array platform object in ECMAScript [ECMA­262]. In particular,this means syntax of the sort filelist.item(0) is at risk; most otherprogrammatic use of FileList is unlikely to be affected by theeventual migration to an Array type.

This interface is a list of File objects.

[Exposed=Window,Worker] interface FileList getter File? item(unsigned long index); readonly attribute unsigned long length; ;

ECMAScript

IDL

Page 20: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 20/51

Example

Sample usage typically involves DOM access to the <inputtype="file"> element within a form, and then accessing selectedfiles.

// 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

7.1. Attributes

lengthmust return the number of files in the FileList object. If there are no files,this attribute must return 0.

7.2. Methods and Parameters

item(index)must return the indexth File object in the FileList. If there is no indexth Fileobject in the FileList, then this method must return null.

index must be treated by user agents as value for the position of a Fileobject in the FileList, with 0 representing the first file. Supported propertyindices [WebIDL] are the numbers in the range zero to one less than thenumber of File objects represented by the FileList object. If there are nosuch File objects, then there are no supported property indices [WebIDL].

NoteThe HTMLInputElement interface [HTML] has a readonly attribute oftype FileList, which is what is being accessed in the aboveexample. Other interfaces with a readonly attribute of type FileListinclude the DataTransfer interface [HTML].

ECMAScript

Page 21: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 21/51

8. Reading Data

8.1 The Read Operation

The algorithm below defines a read operation, which takes a Blob and asynchronous flag as input, and reads bytes into a byte stream which is returned asthe result of the read operation, or else fails along with a failure reason. Methods inthis specification invoke the read operation with the synchronous flag either set orunset.

The synchronous flag determines if a read operation is synchronous orasynchronous, and is unset by default. Methods may set it. If it is set, the readoperation takes place synchronously. Otherwise, it takes place asynchronously.

To perform a read operation on a Blob and the synchronous flag, run the followingsteps:

1. Let s be a a new body, b be the Blob to be read from, and bytes initially set toan empty byte sequence. Set the length on s to the size of b. While there arestill bytes to be read in b perform the following substeps:

Note

The algorithm assumes that invoking methods have checkedfor readability state. A Blob in the CLOSED state must not have aread operation called on it.

1. If the synchronous flag is set, follow the steps below:

1. Let bytes be the byte sequence that results from reading a chunkfrom b. If an error occurs reading a chunk from b, return s with theerror flag set, along with a failure reason, and terminate thisalgorithm.

Note

Along with returning failure, the synchronous part ofthis algorithm must return the failure reason thatoccurred for throwing an exception by synchronousmethods that invoke this algorithm with thesynchronous flag set.

2. If there are no errors, push bytes to s, and increment s'stransmitted [Fetch] by the number of bytes in bytes. Reset bytesto the empty byte sequence and continue reading chunks asabove.

Page 22: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 22/51

3. When all the bytes of b have been read into s, return s andterminate this algorithm.

2. Otherwise, the synchronous flag is unset. Return s and process the restof this algorithm asynchronously.

3. Let bytes be the byte sequence that results from reading a chunk fromb. If an error occurs reading a chunk from b, set the error flag on s, andterminate this algorithm with a failure reason.

Note

The asynchronous part of this algorithm must signal thefailure reason that occurred for asynchronous errorreporting by methods expecting s and which invoke thisalgorithm with the synchronous flag unset.

4. If no error occurs, push bytes to s, and increment s's transmitted[Fetch] by the number of bytes in bytes. Reset bytes to the empty bytesequence and continue reading chunks as above.

To perform an annotated task read operation on a Blob b, perform thesteps below:

1. Perform a read operation on b with the synchronous flag unset, alongwith the additional steps below.

2. If the read operation terminates with a failure reason, queue a task toprocess read error with the failure reason and terminate thisalgorithm.

3. When the first chunk is being pushed to the body s during the readoperation, queue a task to process read.

4. Once the body s from the read operation has at least one chunk readinto it, or there are no chunks left to read from b, queue a task toprocess read data. Keep queuing tasks to process read data for everychunk read or every 50ms, whichever is least frequent.

5. When all of the chunks from b are read into the body s from the readoperation, queue a task to process read EOF.

Use the file reading task source for all these tasks.

8.2. The File Reading Task Source

This specification defines a new generic task source called the file reading tasksource, which is used for all tasks that are queued in this specification to read bytesequences associated with Blob and File objects. It is to be used for features that

Page 23: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 23/51

trigger in response to asynchronously reading binary data.

8.3 The FileReader API

[Constructor, Exposed=Window,Worker] interface FileReader: 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 attributes attribute EventHandler onloadstart; attribute EventHandler onprogress; attribute EventHandler onload; attribute EventHandler onabort; attribute EventHandler onerror; attribute EventHandler onloadend;

;

8.3.1. Constructors

When the FileReader() constructor is invoked, the user agent must return a newFileReader object.

In environments where the global object is represented by a Window or aWorkerGlobalScope object, the FileReader constructor must be available.

8.3.2. Event Handler Attributes

IDL

Page 24: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 24/51

The following are the event handler attributes (and their corresponding eventhandler event types) that user agents must support on FileReader as DOMattributes:

event handler attribute event handler event typeonloadstart loadstart

onprogress progress

onabort abort

onerror error

onload load

onloadend loadend

8.3.3. FileReader States

The FileReader object can be in one of 3 states. The readyState attribute, ongetting, must return the current state, which must be one of the following values:

EMPTY (numeric value 0)The FileReader object has been constructed, and there are no pendingreads. None of the read methods have been called. This is the default stateof a newly minted FileReader object, until one of the read methods havebeen called on it.

LOADING (numeric value 1)A File or Blob is being read. One of the read methods is being processed,and no error has occurred during the read.

DONE (numeric value 2)The entire File or Blob has been read into memory, OR a file error occurredduring read, OR the read was aborted using abort(). The FileReader is nolonger reading a File or Blob. If readyState is set to DONE it means at leastone of the read methods have been called on this FileReader.

8.3.4. Reading a File or Blob

Multiple Reads

The FileReader interface makes available three asynchronous read methods ­readAsArrayBuffer, readAsText, and readAsDataURL, which read files into memory. Ifmultiple concurrent read methods are called on the same FileReader object, useragents must throw an InvalidStateError [DOM4] on any of the read methods thatoccur when readyState = LOADING.

8.3.4.1. The result attribute

On getting, the result attribute returns a Blob's data as a DOMString, or as anArrayBuffer [TypedArrays], or null, depending on the read method that has been

Page 25: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 25/51

called on the FileReader, and any errors that may have occurred. The list below isnormative for the result attribute and is the conformance criteria for this attribute:

On getting, if the readyState is EMPTY (no read method has been called) thenthe result attribute must return null.

On getting, if an error in reading the File or Blob has occurred (using anyread method), then the result attribute must return null.

On getting, if the readAsDataURL read method is used, the result attributemust return a DOMString that is a Data URL [DataURL] encoding of the Fileor Blob's data.

On getting, if the readAsText read method is called and no error in readingthe File or Blob has occurred, then the result attribute must return a stringrepresenting the File or Blob's data as a text string, and should decode thestring into memory in the format specified by the encoding determination as aDOMString.

On getting, if the readAsArrayBuffer read method is called and no error inreading the File or Blob has occurred, then the result attribute must returnan ArrayBuffer [TypedArrays] object.

8.3.4.2. The readAsDataURL(blob) method

When the readAsDataURL(blob) method is called, the user agent must run the stepsbelow.

1. If readyState = LOADING throw an InvalidStateError exception [DOM4] andterminate this algorithm.

Note: The readAsDataURL() method returns due to the algorithm beingterminated.

2. If the blob is in the CLOSED readability state, set the error attribute of thecontext object to return an InvalidStateError DOMError and fire a progressevent called error at the context object. Terminate this algorithm.

3. Otherwise set readyState to LOADING.

4. Initiate an annotated task read operation using the blob argument as inputand handle tasks queued on the file reading task source per below.

5. To process read error with a failure reason, proceed to the error steps.

6. To process read fire a progress event called loadstart at the context object.

7. To process read data fire a progress event called progress at the contextobject.

8. To process read EOF run these substeps:

Page 26: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 26/51

1. Set readyState to DONE.

2. Set the result attribute to the body returned by the read operation as aDataURL [DataURL]; on getting, the result attribute returns the blob asa Data URL [DataURL].

Use the blob's type attribute as part of the Data URL if it isavailable in keeping with the Data URL specification [DataURL].

If the type attribute is not available on the blob return a Data URLwithout a media­type. [DataURL].

Data URLs that do not have media­types [RFC2046] must betreated as plain text by conforming user agents. [DataURL].

3. Fire a progress event called load at the context object.

4. Unless readyState is LOADING fire a progress event called loadend at thecontext object. If readyState is LOADING do NOT fire loadend at thecontext object.

9. Terminate this algorithm.

8.3.4.3. The readAsText(blob, label) method

The readAsText() method can be called with an optional parameter, label, whichis a DOMString argument that represents the label of an encoding [EncodingSpecification]; if provided, it must be used as part of the encoding determinationused when processing this method call.

When the readAsText(blob, label) method is called (the label argument isoptional), the user agent must run the steps below.

1. If readyState = LOADING throw an InvalidStateError [DOM4] and terminatethese steps.

Note: The readAsText() method returns due to the algorithm beingterminated.

2. If the blob is in the CLOSED readability state, set the error attribute of thecontext object to return an InvalidStateError DOMError and fire a progressevent called error at the context object. Terminate this algorithm.

3. Otherwise set readyState to LOADING.

4. Initiate an annotated task read operation using the blob argument as inputand handle tasks queued on the file reading task source per below.

5. To process read error with a failure reason, proceed to the error steps.

6. To process read fire a progress event called loadstart at the context object.

Page 27: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 27/51

7. To process read data fire a progress event called progress at the contextobject.

8. To process read EOF run these substeps:

1. Set readyState to DONE

2. Set the result attribute to the body returned by the read operation,represented as a string in a format determined by the encodingdetermination.

3. Fire a progress event called load at the context object.

4. Unless readyState is LOADING fire a progress event called loadend at thecontext object. If readyState is LOADING do NOT fire loadend at thecontext object.

9. Terminate this algorithm.

8.3.4.4. The readAsArrayBuffer(blob) method

When the readAsArrayBuffer(blob) method is called, the user agent must run thesteps below.

1. If readyState = LOADING throw an InvalidStateError exception [DOM4] andterminate these steps.

Note: The readAsArrayBuffer() method returns due to the algorithm beingterminated.

2. If the blob is in the CLOSED readability state, set the error attribute of thecontext object to return an InvalidStateError DOMError and fire a progressevent called error at the context object. Terminate this algorithm.

Note: The readAsArrayBuffer() method returns due to the algorithm beingterminated.

3. Otherwise set readyState to LOADING.

4. Initiate an annotated task read operation using the blob argument as inputand handle tasks queued on the file reading task source per below.

5. To process read error with a failure reason, proceed to the error steps.

6. To process read fire a progress event called loadstart at the context object.

7. To process read data fire a progress event called progress at the contextobject.

8. To process read EOF run these substeps:

1. Set readyState to DONE

Page 28: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 28/51

2. Set the result attribute to the body returned by the read operation asan ArrayBuffer [TypedArrays] object.

3. Fire a progress event called load at the context object.

4. Unless readyState is LOADING fire a progress event called loadend at thecontext object. If readyState is LOADING do NOT fire loadend at thecontext object.

9. Terminate this algorithm.

8.3.4.5. Error Steps

These error steps are to process read error with a failure reason.

1. Set the context object's readyState to DONE and result to null if it is notalready set to null.

2. Set the error attribute on the context object; on getting, the error attributemust be a a DOMError object that corresponds to the failure reason. Fire aprogress event called error at the context object.

3. Unless readyState is LOADING, fire a progress event called loadend at thecontext object. If readyState is LOADING do NOT fire loadend at the contextobject.

4. Terminate the algorithm for any read method.

Note: The read method returns due to the algorithm being terminated.

8.3.4.6. The abort() method

When the abort() method is called, the user agent must run the steps below:

1. If readyState = EMPTY or if readyState = DONE set result to null and terminatethis algorithm.

2. If readyState = LOADING set readyState to DONE and result to null.

3. If there are any tasks from the context object on the file reading task sourcein an affiliated task queue, then remove those tasks from that task queue.

4. Terminate the algorithm for the read method being processed.

5. Fire a progress event called abort

6. Fire a progress event called loadend.

8.3.4.7. Blob Parameters

Page 29: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 29/51

The three asynchronous read methods, the three synchronous read methods,URL.createObjectURL and URL.createFor take a Blob parameter. This sectiondefines this parameter.

blobThis is a Blob argument and must be a reference to a single File in aFileList or a Blob argument not obtained from the underlying OS file system.

8.4. Determining Encoding

When reading blob objects using the readAsText() read method, the followingencoding determination steps must be followed:

1. Let encoding be null

2. If the label argument is present when calling the method, set encoding to theresult of "getting an encoding" using the Encoding Specification [EncodingSpecification] for label.

3. If the "getting an encoding" steps above return failure, then set encoding tonull.

4. If encoding is null, and the blob argument's type attribute is present, and ituses a Charset Parameter [RFC2046], set encoding to the result of "gettingan encoding" using the Encoding Specification [Encoding Specification] forthe portion of the Charset Parameter that is a label of an encoding.

Example

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 thatuser agents must parse and extract the portion of the CharsetParameter that constitutes a label of an encoding.

5. If the "getting an encoding" steps above return failure, then set encoding tonull.

6. If encoding is null, then set encoding to utf­8.

7. "Decode" [Encoding Specification] this blob using fallback encodingencoding, and return the result. On getting, the result attribute of theFileReader object returns a string in encoding format. The synchronousreadAsText method of the FileReaderSync object returns a string in encodingformat.

8.5.10. Events

The FileReader object must be the event target for all events in this specification.

Page 30: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 30/51

When this specification says to fire a progress event called e (for someProgressEvent e at a given FileReader reader as the context object), the followingare normative:

The progress event e does not bubble. e.bubbles must be false [DOM4]

The progress event e is NOT cancelable. e.cancelable must be false [DOM4]

The term "fire an event" is defined in DOM Core [DOM4]. Progress Eventsare defined in Progress Events [ProgressEvents].

8.5.10.1. Event Summary

The following are the events that are fired at FileReader objects; firing events isdefined in DOM Core [DOM4].

Eventname

Interface Fired when…

loadstart ProgressEvent When the read starts.progress ProgressEvent While reading (and decoding) blobabort ProgressEvent When the read has been aborted. For instance, by

invoking the abort() method.error ProgressEvent When the read has failed (see errors).load ProgressEvent When the read has successfully completed.loadend ProgressEvent When the request has completed (either in success or

failure).

8.5.10.2. Summary of Event Invariants

This section is informative. The following are invariants applicable to event firingfor a given asynchronous read method in this specification:

1. Once a loadstart has been fired, a corresponding loadend fires atcompletion of the read, EXCEPT if

the read method has been cancelled using abort() and a new readmethod has been invoked;

the event handler function for a load event initiates a new read;

the event handler function for a error event initiates a new read.

NoteThe events loadstart and loadend are not coupled in a one­to­one manner.

Example

Page 31: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 31/51

This example showcases "read­chaining" namely initiatinganother read from within an event handler while the "first" readcontinues 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

2. One progress event will fire when blob has been completely read intomemory.

3. No progress event fires before loadstart.

4. No progress event fires after any one of abort, load, and error have fired. Atmost one of abort, load, and error fire for a given read.

5. No abort, load, or error event fires after loadend.

8.6 Reading on Threads

Web Workers allow for the use of synchronous File or Blob read APIs, since suchreads on threads do not block the main thread. This section defines a synchronousAPI, which can be used within Workers [Web Workers]. Workers can avail of boththe asynchronous API (the FileReader object) and the synchronous API (theFileReaderSync object).

8.6.1. The FileReaderSync API

This interface provides methods to synchronously read File or Blob objects intomemory.

[Constructor, Exposed=Worker]

ECMAScript

IDL

Page 32: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 32/51

interface FileReaderSync

// Synchronously return strings

ArrayBuffer readAsArrayBuffer(Blob blob); DOMString readAsText(Blob blob, optional DOMString label); DOMString readAsDataURL(Blob blob); ;

8.6.1.1. Constructors

When the FileReaderSync() constructor is invoked, the user agent must return anew FileReaderSync object.

In environments where the global object is represented by a WorkerGlobalScopeobject, the FileReaderSync constructor must be available.

8.6.1.2. The readAsText method

When the readAsText(blob, label) method is called (the label argument isoptional), the following steps must be followed:

1. If readyState = LOADING throw an InvalidStateError exception [DOM4] andterminate these steps.

Note: The method returns due to the algorithm being terminated.

2. If the blob has been closed through the close method, throw anInvalidStateError exception [DOM4] and terminate this algorithm.

Note: The method returns due to the algorithm being terminated.

3. Otherwise, initiate a read operation using the blob argument, and with thesynchronous flag set. If the read operation returns failure, throw theappropriate exception. Terminate this algorithm.

4. If no error has occurred, return the result of the read operation representedas a string in a format determined through the encoding determinationalgorithm.

8.6.1.3. The readAsDataURL method

When the readAsDataURL(blob) method is called, the following steps must befollowed:

1. If readyState = LOADING throw an InvalidStateError exception [DOM4] andterminate these steps.

Page 33: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 33/51

Note: The method returns due to the algorithm being terminated.

2. If the blob has been closed through the close method, throw anInvalidStateError exception [DOM4] and terminate this algorithm.

Note: The method returns due to the algorithm being terminated.

3. Otherwise, initiate a read operation using the blob argument, and with thesynchronous flag set. If the read operation returns failure, throw theappropriate exception. Terminate this algorithm.

4. If no error has occurred, return the result of the read operation as a DataURL [DataURL] subject to the considerations below.

Use the blob's type attribute as part of the Data URL if it is available inkeeping with the Data URL specification [DataURL] .

If the type attribute is not available on the blob return a Data URLwithout a media­type. [DataURL].

Data URLs that do not have media­types [RFC2046] must be treatedas plain text by conforming user agents. [DataURL].

8.6.1.4. The readAsArrayBuffer method

When the readAsArrayBuffer(blob) method is called, the following steps must befollowed:

1. If readyState = LOADING throw an InvalidStateError exception [DOM4] andterminate these steps.

Note: The method returns due to the algorithm being terminated.

2. If the blob has been closed through the close method, throw anInvalidStateError exception [DOM4] and terminate this algorithm.

Note: The method returns due to the algorithm being terminated.

3. Otherwise, initiate a read operation using the blob argument, and with thesynchronous flag set. If the read operation returns failure, throw theappropriate exception. Terminate this algorithm.

4. If no error has occurred, return the result of the read operation as anArrayBuffer [TypedArrays].

9. Errors and Exceptions

Error conditions can occur when reading files from the underlying filesystem. Thelist below of potential error conditions is informative.

The File or Blob being accessed may not exist at the time one of the

Page 34: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 34/51

asynchronous read methods or synchronous read methods are called. Thismay be due to it having been moved or deleted after a reference to it wasacquired (e.g. concurrent modification with another application). SeeNotFoundError

A File or Blob may be unreadable. This may be due to permission problemsthat occur after a reference to a File or Blob has been acquired (e.g.concurrent lock with another application). Additionally, the snapshot statemay have changed. See NotReadableError

User agents MAY determine that some files are unsafe for use within Webapplications. A file may change on disk since the original file selection, thusresulting in an invalid read. Additionally, some file and directory structuresmay be considered restricted by the underlying filesystem; attempts to readfrom them may be considered a security violation. See the securityconsiderations. See SecurityError

9.1. Throwing an Exception or Returning an Error

This section is normative. Error conditions can arise when reading a File or aBlob.

The read operation can terminate due to error conditions when reading a File or aBlob; the particular error condition that causes a read operation to return failure orqueue a task to process read error is called a failure reason.

Synchronous read methods throw exceptions of the type in the table below if therehas been an error owing to a particular failure reason.

Asynchronous read methods use the error attribute of the FileReader object,which must return a DOMError object [DOM4] of the most appropriate type fromthe table below if there has been an error owing to a particular failure reason, orotherwise return null.

Type Description and Failure ReasonNotFoundError If the File or Blob resource could not be found at the time the

read was processed, this is the NotFound failure reason. Forasynchronous read methods the error attribute must return a"NotFoundError" DOMError and synchronous read methods mustthrow a NotFoundError exception.

SecurityError If:

it is determined that certain files are unsafe for accesswithin a Web application, this is the UnsafeFile failurereason.

it is determined that too many read calls are being madeon File or Blob resources, this is the TooManyReadsfailure reason.

Page 35: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 35/51

For asynchronous read methods the error attribute may returna "SecurityError" DOMError and synchronous read methodsmay throw a SecurityError exception.

This is a security error to be used in situations not covered byany other failure reason.

NotReadableError If:

the snapshot state of a File or a Blob does not match thestate of the underlying storage, this is theSnapshotState failure reason.

the File or Blob cannot be read, typically due due topermission problems that occur after a snapshot statehas been established (e.g. concurrent lock on theunderlying storage with another application) then this isthe FileLock failure reason.

For asynchronous read methods the error attribute must returna "NotReadableError" DOMError and synchronous read methodsmust throw a NotReadableError exception.

10. A URL for Blob and File reference

This section defines a scheme for a URL used to refer to Blob objects (and Fileobjects).

10.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 andis an informative discussion.

This scheme should be able to be used with web APIs such asXMLHttpRequest [XHR], and with elements that are designed to be used withHTTP URLs, such as the img element [HTML]. In general, this schemeshould be designed to be used wherever URLs can be used on the web.

This scheme should have defined response codes, so that web applicationscan 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 allowsafe 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

Page 36: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 36/51

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 thatthey no longer refer to Blob objects. This includes scenarios where filereferences are no longer needed by a program, but also other uses of Blobobjects. Consider a scenario where a Blob object can be exported from adrawing program which uses the canvas element and API [HTML]. Asnapshot of the drawing can be created by exporting a Blob. This schemecan be used with the img [HTML] element to display the snapshot; if the userdeletes the snapshot, any reference to the snapshot in memory via a URLshould be invalid, and hence the need to be able to revoke such a URL.

10.2. Discussion of Existing Schemes

This section is an informative discussion of existing schemes that may have beenrepurposed or reused for the use cases for URLs above, and justification for why anew scheme is considered preferable. These schemes include HTTP [RFC7230],file [RFC1630][RFC1738], and a scheme such as urn:uuid [RFC4122]. One broadconsideration in determining what scheme to use is providing something withintuitive appeal to web developers.

HTTP could be repurposed for the use cases mentioned above; it alreadycomes with well­defined request­response semantics that are already usedby web applications. But Blob resources 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 agentsautomatically "proxy" the underlying file system on the local machine via anHTTP server (e.g. with URLs of the sort http://localhost), HTTP is nottraditionally used with local resources. Moreover, an important use case forthese URLs are that they can be revoked with an API call. HTTP URLs havetraditionally been used for resources that may be more permanent (and thatare certainly not chiefly memory­resident, such as files that a web applicationcan read). Reusing the HTTP scheme might be confusing for web developersowing to well­established practice.

The reuse of file URLs would involve changes to file URL use today, such asadding response codes. While they are used inconsistently in webapplications, the structure of the URLs would change, and request­responsebehavior 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 isimprudent, given legacy usage. Additionally, the use cases for a Blob URLscheme call for uses beyond the file system.

A scheme of the sort urn:uuid [RFC4122] could be used, though use of thisscheme is unprecedented in HTML and JavaScript web applications. Theurn:uuid scheme is very generic. URLs in the scheme urn:uuid have thedisadvantage of unfamiliarity and inconsistency across the web platform. Anew scheme has the advantage of being explicit about what is being

Page 37: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 37/51

referenced. In theory, URLs make no guarantee about what sort of resourceis obtained when they are dereferenced; that is left to content labeling andmedia type. But in practice, the name of the scheme creates an expectationabout both the resource and the protocol of the request­responsetransaction. Choosing a name that clarifies the primary use case ­ namely,access to memory­resident Blob resources ­ is a worthwhile compromise,and favors clarity, familiarity, and consistency across the web platform.

10.3. The Blob URL

A Blob URL must consist of the blob: scheme followed by scheme data which mustconsist of a string tuple comprising the origin of the Blob URL, the "/" (U+0024SOLIDUS) character, and a UUID [RFC4122; for an ABNF of UUID, see AppendixA]. A Blob URL may contain an optional fragment. The Blob URL is serialized as astring according to the Unicode Serialization of a Blob URL algorithm.

A fragment, if used, has a distinct interpretation depending on the media type ofthe Blob or File resource in question (see fragment discussion).

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 Appendix A ; fragIdentifier is optional and as defined in [RFC3986] and Appendix A

An example of a Blob URL might beblob:https://example.org/9115d58c­bcda­ff47­86e5­083e9a215304.

10.3.1. Origin of Blob URLs

Blob URLs are created using URL.createObjectURL and/or URL.createFor, and arerevoked using URL.revokeObjectURL. The origin of a Blob URL must be the sameas the effective script origin specified by the incumbent settings object at the timethe method that created it ­­ either URL.createObjectURL or URL.createFor ­­ wascalled. The origin of a Blob URL, when serialized as a string, must conform to theWeb Origin Specification's Unicode Serialization of an Origin algorithm [ORIGIN].Cross­origin requests on Blob URLs must return a network error.

Note

ABNF

Page 38: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 38/51

In practice this means that HTTP and HTTPS origins are covered bythis specification as valid origins for use with Blob URLs. Thisspecification 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, which ispart of the Blob URL's scheme data) may have behavior that isundefined, even though user agents may treat such Blob URLs asvalid.

10.3.2. Unicode Serialization of a Blob URL

The Unicode Serialization of a Blob URL is the value returned by the followingalgorithm, which is invoked by URL.createObjectURL and/or URL.createFor:

1. Let result be the empty string. Append the string "blob" (that is, the Unicodecode point sequence U+0062, U+006C, U+006F, U+0062) to result.

2. Append the ":" (U+003A COLON) character to result.

3. Let O be the origin of the Blob URL. If the Unicode Serialization of an Originalgorithm [ORIGIN] on O returns null, user agents may substitute animplementation defined value for the return value of the Unicode Serializationof an Origin algorithm. Append the result of the Unicode Serialization of anOrigin algorithm for O [ORIGIN] to result.

4. Append the "/" character (U+0024 SOLIDUS) to result.

5. Generate a UUID [RFC4122] as a Unicode string and append it to result.

6. Return result.

10.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 isonly 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 useragent does not recognize the media type of the resource, OR if a fragment is notmeaningful within the resource, it must ignore the fragment. The fragment must notbe used to identify a resource; only the blob: scheme and the scheme dataconstitute a valid resource identifier.

A valid Blob URL reference could look like:blob:http://example.org:8080/550e8400‐e29b‐41d4‐a716‐446655440000#aboutABBAwhere "#aboutABBA" might be an HTML fragment identifier referring to an elementwith an id attribute of "aboutABBA".

Note

Page 39: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 39/51

The fragment is not used to identify the resource. Neither theURL.createObjectURL method nor the URL.createFor method generatea fragment.

10.4. Dereferencing Model for Blob URLs

Note

The URL and Fetch Specifications should be considered normativefor parsing and fetching Blob URLs. The section below is forinformational purposes only, and is not considered normative.

Blob URLs are dereferenced when the user agent retrieves the resource identifiedby the Blob URL and returns it to the requesting entity. This section providesguidance on requests and responses.

Only requests with GET [RFC7231] are supported. Specifically, responses are onlya subset of the following from HTTP [RFC7231]:

10.4.1. 200 OK

This response is used if the request has succeeded, and no network errors aregenerated.

10.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 andprocess that media type in a manner consistent with the Mime Sniffingspecification [MIMESNIFF].

If a resource identified with a Blob URL is a File object, user agents use that file'sname attribute, as if the response had a Content‐Disposition header with thefilename parameter set to the File's name attribute [RFC6266].

Note

A corollary to this is a non­normative implementation guideline: thatthe "File Save As" user interface in user agents takes into accountthe File's name attribute if presenting a default name to save the fileas.

Page 40: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 40/51

10.4.3. Network Errors

Responses that do not succeed with a 200 OK act as if a network error hasoccurred [Fetch]. 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 anentry in the Blob URL Store.

A cross­origin request is made on a Blob URL.

A security error has occurred.

10.4.4. Sample Request and Response Headers

Note

This section is informative.

This section provides sample exchanges between web applications and useragents using Blob URLs. A request can be triggered using HTML markup of thesort <img src="blob:http://example.org:8080/550e8400‐e29b‐41d4‐a716‐446655440000">. These examples merely illustrate the request and response; webdevelopers are not likely to interact with all the headers, but thegetAllResponseHeaders() method of XMLHttpRequest, if used, will show relevantresponse headers [XHR].

Example

Requests could look like this:

GET http://example.org:8080/550e8400‐e29b‐41d4‐a716‐446655440000

If the blob has an affiliated media type [RFC2046] represented by itstype attribute, then the response message should include theContent­Type header from RFC7231 [RFC7231]. See processingmedia types.

200 OK

HEADERS

HEADERS

Page 41: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 41/51

Content‐Type: image/jpeg Content‐Length: 21897 ....

If there is a file error associated with the blob, then a user agent actsas if a network error has occurred.

10.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 networkerror has occurred. This section describes a supplemental interface to the URLspecification [URL API] and presents methods for Blob URL creation andrevocation.

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 exposea prototype property on the URL interface object unless the user agent alsoimplements the URL [URL API] specification. In other words, URL.prototype mustevaluate to true if the user agent implements the URL [URL API] specification, andmust NOT evaluate to true otherwise.

10.5.1. Methods and Parameters

The createObjectURL static methodReturns a unique Blob URL. This method must act as follows:

1. If called with a Blob argument that has a readability state of CLOSED,user agents must return the output of the Unicode Serialization of anBlob URL.

IDL

Page 42: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 42/51

Note

No entry is added to the Blob URL Store; consequently,when this Blob URL is dereferenced, a network erroroccurs.

2. Otherwise, user agents must run the following sub­steps:

1. Let url be the result of the Unicode Serialization of a Blob URLalgorithm.

2. Add an entry to the Blob URL Store for url and blob.

3. Return url.

The createFor static methodReturns a unique Blob URL; Blob URLs created with this method are said tobe auto­revoking since user­agents are responsible for the revocation ofBlob URLs created with this method, subject to the lifetime stipulation forBlob URLs. This method must act as follows:

1. If called with a Blob argument that has a readability state of CLOSED,user agents must return the output of the Unicode Serialization of aBlob URL.

Note

No entry is added to the Blob URL Store; consequently,when this Blob URL is dereferenced, a network erroroccurs.

2. Otherwise, user agents must run the following steps:

1. Let url be the result of the Unicode Serialization of a Blob URL.

2. Add an entry to the Blob URL Store for url and blob.

3. Add an entry to the Revocation List for url.

4. Return url.

Example

In the example below, after obtaining a reference to a Blobobject (in this case, a user­selected File from the underlyingfile system), the static method URL.createObjectURL() is calledon that Blob object.

var file = document.getElementById('file').files[0];

ECMAScript

Page 43: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 43/51

if(file) blobURLref = window.URL.createObjectURL(file); myimg.src = blobURLref;

....

The revokeObjectURL static methodRevokes the Blob URL provided in the string url by removing thecorresponding entry from the Blob URL Store. This method must act asfollows:

1. If the url refers to a Blob that has a readability state of CLOSED OR if thevalue provided for the url argument is not a Blob URL, OR if the valueprovided for the url argument does not have an entry in the Blob URLStore, this method call does nothing. User agents may display amessage on the error console.

2. Otherwise, user agents must remove the entry from the Blob URL Storefor url.

Note

Subsequent attemps to dereference url result in anetwork error, since the entry has been removed from theBlob URL Store.

The url argument to the revokeObjectURL method is a Blob URL string.

Example

In the example below, window1 and window2 are separate, but inthe same origin; window2 could be an iframe [HTML] insidewindow1.

myurl = window1.URL.createObjectURL(myblob); window2.URL.revokeObjectURL(myurl);

Since window1 and window2 are in the same origin and share thesame Blob URL Store, the URL.revokeObjectURL call ensures

ECMAScript

Page 44: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 44/51

that subsequent dereferencing of myurl results in a the useragent acting as if a network error has occurred.

10.5.2. Examples of Blob URL Creation and Revocation

Blob URLs are strings that are used to dereference Blob objects, and can persistfor as long as the document from which they were minted usingURL.createObjectURL() or URL.createFor ­ see Lifetime of Blob URLs.

This section gives sample usage of creation and revocation of Blob URLs withexplanations.

Examples

In the example below, two img elements [HTML] refer to the sameBlob URL:

<script>url = URL.createObjectURL(blob); </script><script> img2.src=url;</script>

In the example below, 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

ECMAScript

ECMAScript

Page 45: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 45/51

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 bothimage objects have been loaded. While not restricting number ofuses of the Blob URL offers more flexibility, it increases the likelihoodof leaks; developers should pair it with a corresponding call toURL.revokeObjectURL.

var blobURLref2 = URL.createFor(file);img1 = new Image();

img1.src = blobURLref2;

....

The example above uses URL.createFor, which allows uses such asthe one above, and obviates the need for a corresponding call by theweb developer to URL.revokeObjectURL.

// 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");

....

The example above uses URL.createFor to mint a Blob URL, andappends a fragment that has an understood meaning within theresource (in this case, it references an anchor within the HTMLdocument).

ECMAScript

ECMAScript

Page 46: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 46/51

10.6. Lifetime of Blob URLs

A global object which exposes URL.createObjectURL or URL.createFor mustmaintain a Blob URL Store which is a list of Blob URLs created by theURL.createObjectURL method or the URL.createFor method, and the blob resourcethat each refers to.

A global object which exposes URL.createFor must maintain a Revocation Listwhich is a list of Blob URLs created with the URL.createFor method.

When this specification says to add an entry to the Blob URL Store for a BlobURL and a blob input, the user­agent must add the Blob URL and a reference tothe blob it refers to to the Blob URL Store.

When this specification says to add an entry to the The Revocation List for aBlob URL, user agents must add the Blob URL to the Revocation List. This is onlyfor auto­revoking Blob URLs.

When this specification says to remove an entry from the Blob URL Store for agiven Blob URL or for a given Blob, user agents must remove the Blob URL andthe blob it refers to from the Blob URL Store. Subsequent attempts to dereferencethis URL must result in a network error.

The Revocation List and the Blob URL Store must be processed together asfollows:

1. Add removing the entries for all the Blob URLs in the Revocation List to theglobal script cleanup jobs list.

2. When all the Blob URLs in the Revocation List have had their correspondingentries in the Blob URL Store removed, remove all the Blob URLs in theRevocation List.

3. This specification adds an additional unloading document cleanup step[HTML]: user agents must remove all Blob URLs from the Blob URL Storewithin that document.

Note

User agents are free to garbage collect resources removed from theBlob URL Store.

11. 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 assuch is subject to some security considerations. This specification also assumes

Page 47: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 47/51

that the primary user interaction is with the <input type="file"/> element of HTMLforms [HTML], and that all files that are being read by FileReader objects have firstbeen selected by the user. Important security considerations include preventingmalicious file selection attacks (selection looping), preventing access to system­sensitive files, and guarding against modifications of files on disk after a selectionhas taken place.

Preventing selection looping. During file selection, a user may bebombarded 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 theFileList object returned be of size 0.

System­sensitive files (e.g. files in /usr/bin, password files, and other nativeoperating system executables) typically should not be exposed to webcontent, and should not be accessed via Blob URLs. User agents may throwa SecurityError exception for synchronous read methods, or return aSecurityError DOMError for asynchronous reads.

Editorial note

This section is provisional; more security data may supplement this insubsequent drafts.

12. Requirements and Use Cases

This section covers what the requirements are for this API, as well as illustratessome 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 toread and parse data directly from a local file programmatically.

Example: A lyrics viewer. User wants to read song lyrics from songs inhis plist file. User browses for plist file. File is opened, read, parsed,and presented to the user as a sortable, actionable list within a webapplication. User can select songs to fetch lyrics. User uses the"browse for file" dialog.

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.

Example: A Calendar App. User's company has a calendar. User wantsto sync local events to company calendar, marked as "busy" slots(without leaking personal info). User browses for file and selects it. Thetext/calendar file is parsed in the browser, allowing the user to mergethe files to one calendar view. The user wants to then save the file backto his local calendar file. (using "Save As" ?). The user can also send

Page 48: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 48/51

the integrated calendar file back to the server calendar storeasynchronously.

User agents should provide the ability to save a local file programmaticallygiven an amount of data and a file name.

Note

While this specification doesn't provide an explicit API call totrigger downloads, the HTML5 specification has addressed this.The download attribute of the a element [HTML] initiates adownload, saving a File with the name specified. Thecombination of this API and the download attribute on aelements allows for the creation of files within web applications,and the ability to save them locally.

Example: A Spreadsheet App. User interacts with a form, andgenerates some input. The form then generates a CSV (CommaSeparated Variables) output for the user to import into a spreadsheet,and uses "Save...". The generated output can also be directlyintegrated into a web­based spreadsheet, and uploadedasynchronously.

User agents should provide a streamlined programmatic ability to send datafrom a file to a remote server that works more efficiently than form­baseduploads today

Example: A Video/Photo Upload App. User is able to select large filesfor upload, which can then be "chunk­transfered" to the server.

User agents should provide an API exposed to script that exposes thefeatures above. The user is notified by UI anytime interaction with the filesystem takes place, giving the user full ability to cancel or abort thetransaction. The user is notified of any file selections, and can cancel these.No invocations to these APIs occur silently without user intervention.

13. Appendix A

This section uses the Augmented Backus­Naur Form (ABNF), defined in[RFC5234] to describe components of blob: URLs.

13.1. An ABNF for UUID

The following is an ABNF [ABNF] for UUID. UUID strings must only use charactersin 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 36characters long.

ABNF

Page 49: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 49/51

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"

13.2 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 = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

14. Acknowledgements

This specification was originally developed by the SVG Working Group. Manythanks to Mark Baker and Anne van Kesteren for their feedback.

Thanks to Robin Berjon for editing the original specification.

ABNF

ABNF

Page 50: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 50/51

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 public­[email protected] listserv

15. References

15.1. Normative references

RFC2119Key words for use in RFCs to Indicate Requirement Levels, S. Bradner.IETF.

HTMLHTML 5: A vocabulary and associated APIs for HTML and XHTML, I.Hickson, R. Berjon, S. Faulkner, T. Leithead, E. Doyle Navara, E. O'Connor,S. Pfeiffer. W3C.

Web Origin ConceptWeb Origin Concept, A. Barth. IETF.

ProgressEventsProgress Events, A. van Kesteren. W3C.

RFC2397The "data" URL Scheme, L. Masinter. IETF.

Web WorkersWeb Workers (work in progress), I. Hickson. W3C.

DOM4DOM4 (work in progress), A. Gregor, A. van Kesteren, Ms2ger. W3C.

UnicodeThe Unicode Standard, Version 5.2.0., J. D. Allen, D. Anderson, et al.Unicode Consortium.

RFC7230Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing, R.Fielding, J. Reschke. IETF.

RFC7231Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content, R. Fielding,J. Reschke. IETF.

RFC2046Multipurpose Internet Mail Extensions (MIME) Part Two: Media Extensions,N. Freed, N. Borenstein. IETF.

RFC6266Use of the Content­Disposition Header Field in the Hypertext TransferProtocol (HTTP), J. Reschke. IETF.

Encoding SpecificationEncoding Living Standard, A. van Kesteren, J. Bell.

Streams SpecificationSreams Living Standard, Domenic Denicola, Takeshi Yoshino.

Typed Arrays

Page 51: File API

6/7/2015 File API

http://www.w3.org/TR/FileAPI/ 51/51

Typed Arrays (work in progress), V. Vukicevic, K. Russell. Khronos Group.RFC5234

Augmented BNF for Syntax Specifications: ABNF, D. Crocker, P. Overell.IETF.

URL SpecificationURL Living Standard (work in progress), A. van Kesteren.

Fetch SpecificationFetch Specification, A. van Kesteren. WHATWG.

WebIDL SpecificationWebIDL (work in progress), C. McCormack.

ECMAScriptECMAScript 5th Edition, A. Wirfs­Brock, P. Lakshman et al.

MIME SniffingMIME Sniffing (work in progress), A. Barth, I. Hickson.

XMLHttpRequestXMLHttpRequest Living Standard, A. van Kesteren.

15.2. Informative References

Google Gears Blob APIGoogle Gears Blob API (deprecated)

RFC4122A Universally Unique IDentifier (UUID) URN Namespace, P. Leach, M.Mealling, R. Salz. IETF.

RFC3986Uniform Resource Identifier (URI): Generic Syntax, T. Berners­Lee, R.Fielding, L. Masinter. IETF.

RFC1630Universal Resource Identifiers in WWW, T. Berners­Lee. IETF.

RFC1738Uniform Resource Locators (URL), T. Berners­Lee, L. Masinter, M. McCahill.IETF.

WebRTC 1.0WebRTC 1.0, A. Bergkvist, D. Burnett, C. Jennings, A. Narayanan. W3C.