File API

Editor’s Draft,

More details about this document
This version:
https://w3c.github.io/FileAPI/
Latest published version:
https://www.w3.org/TR/FileAPI/
Feedback:
GitHub
Inline In Spec
Editor:
(Google)
Former Editor:
Arun Ranganathan(Mozilla Corporation)
Tests:
web-platform-tests FileAPI/(ongoing work)

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:

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

§ 10 Requirements and Use Casescovers the motivation behind this specification.

This API is designed to be used in conjunction with other APIs and elements on the web platform, notably:XMLHttpRequest(e.g. with an overloadedsend()method forFileorBlobarguments),postMessage(),DataTransfer(part of the drag and drop API defined in[HTML]) and Web Workers. Additionally, it should be possible to programmatically obtain a list of files from theinputelement when it is in theFile Uploadstate[HTML]. These kinds of behaviors are defined in the appropriate affiliated specifications.

Status of this document

This section describes the status of this document at the time of its publication. A list of currentW3Cpublications and the latest revision of this technical report can be found in theW3Ctechnical reports indexat https://www.w3.org/TR/.

This document was published by theWeb Applications Working Groupas an Editors Draft. This document is intended to become a W3C Recommendation.

Previous discussion of this specification has taken place on two other mailing lists:[email protected](archive) and[email protected](archive). Ongoing discussion will be on the[email protected]mailing list.

This draft consists of changes made to the previous Last Call Working Draft. Please send comments to the[email protected]as described above. You can see Last Call Feedback on the W3C Wiki:https://www.w3.org/wiki/Webapps/LCWD-FileAPI-20130912

Animplementation reportis automatically generated from the test suite.

This document was published by theWeb Applications Working Groupas a Working Draft. Feedback and comments on this specification are welcome. Please useGitHub issuesHistorical discussions can be found in the[email protected] archives.

Publication as an Editors Draft does not imply endorsement byW3Cand its Members. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under theW3CPatent Policy.W3Cmaintains apublic list of any patent disclosuresmade in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes containsEssential Claim(s)must disclose the information in accordance withsection 6 of theW3CPatent Policy.

This document is governed by the03 November 2023 W3C Process Document.

1.Introduction

This section is informative.

Web applications should have the ability to manipulate as wide as possible a range of user input, including files that a user may wish to upload to a remote server or manipulate inside a rich web application. This specification defines the basic representations for files, lists of files, errors raised by access to files, and programmatic ways to read files. Additionally, this specification also defines an interface that represents "raw data" which can be asynchronously processed on the main thread of conforming user agents. The interfaces and API defined in this specification can be used with other interfaces and APIs exposed to the web platform.

TheFileinterface represents file data typically obtained from the underlying file system, and theBlobinterface ( "Binary Large Object" - a name originally introduced to web APIs inGoogle Gears) represents immutable raw data.FileorBlobreads should happen asynchronously on the main thread, with an optional synchronous API used within threaded web applications. An asynchronous API for reading files prevents blocking and UI "freezing" on a user agent’s main thread. This specification defines an asynchronous API based on anevent modelto read and access aFileorBlob’s data. AFileReaderobject provides asynchronous read methods to access that file’s data through event handler content attributes and the firing of events. The use of events and event handlers allows separate code blocks the ability to monitor theprogress of the read(which is particularly useful for remote drives or mounted drives, where file access performance may vary from local drives) and error conditions that may arise during reading of a file. An example will be illustrative.

In the example below, different code blocks handle progress, error, and success conditions.
functionstartRead(){
// obtain input element through DOM

varfile=document.getElementById('file').files[0];
if(file){
getAsText(file);
}
}

functiongetAsText(readFile){

varreader=newFileReader();

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

functionupdateProgress(evt){
if(evt.lengthComputable){
// evt.loaded and evt.total are ProgressEvent properties
varloaded=(evt.loaded/evt.total);
if(loaded<1){
// Increase the prog bar length
// style.width = (loaded * 200) + "px";
}
}
}

functionloaded(evt){
// Obtain the read file data
varfileString=evt.target.result;
// Handle UTF-16 file dump
if(utils.regexp.isChinese(fileString)){
//Chinese Characters + Name validation
}
else{
// run other charset test
}
// xhr.send(fileString)
}

functionerrorHandler(evt){
if(evt.target.error.name=="NotReadableError"){
// The file could not be read
}
}

2.Terminology and Algorithms

When this specification says toterminate an algorithmthe user agent must terminate the algorithm after finishing the step it is on. Asynchronousread methodsdefined in this specification may return before the algorithm in question is terminated, and can be terminated by anabort()call.

The algorithms and steps in this specification use the following mathematical operations:

The termUnix Epochis used in this specification to refer to the time 00:00:00 UTC on January 1 1970 (or 1970-01-01T00:00:00Z ISO 8601); this is the same time that is conceptually "0"in ECMA-262[ECMA-262].

Theslice blobalgorithm given aBlobblob,start,end,andcontentTypeis used to refer to the following steps and returns a newBlobcontaining the bytes ranging from thestartparameter up to but not including theendparameter. It must act as follows:
  1. LetoriginalSizebeblob’ssize.

  2. Thestartparameter, if non-null, is a value for the start point of aslice blobcall, and must be treated as a byte-order position, with the zeroth position representing the first byte. User agents must normalizestartaccording to the following:

    1. Ifstartis null, letrelativeStartbe 0.
    2. Ifstartis negative, letrelativeStartbemax((originalSize+start), 0).
    3. Otherwise, letrelativeStartbemin(start,originalSize).
  3. Theendparameter, if non-null. is a value for the end point of aslice blobcall. User agents must normalizeendaccording to the following:

    1. Ifendis null, letrelativeEndbeoriginalSize.
    2. Ifendis negative, letrelativeEndbemax((originalSize+end), 0).
    3. Otherwise, letrelativeEndbemin(end,originalSize).
  4. ThecontentTypeparameter, if non-null, is used to set the ASCII-encoded string in lower case representing the media type of theBlob.User agents must normalizecontentTypeaccording to the following:

    1. IfcontentTypeis null, letrelativeContentTypebe set to the empty string.
    2. Otherwise, letrelativeContentTypebe set tocontentTypeand run the substeps below:
      1. IfrelativeContentTypecontains any characters outside the range of U+0020 to U+007E, then setrelativeContentTypeto the empty string and return from these substeps.

      2. Convert every character inrelativeContentTypetoASCII lowercase.

  5. Letspanbemax((relativeEnd-relativeStart), 0).

  6. Return a newBlobobjectSwith the following characteristics:

    1. Srefers tospanconsecutivebytes fromblob’s associatedbytesequence, beginning with thebyteat byte-order positionrelativeStart.
    2. S.size=span.
    3. S.type=relativeContentType.

3.The Blob Interface and Binary Data

ABlobobject refers to abytesequence, and has asizeattribute which is the total number of bytes in the byte sequence, and atypeattribute, which is an ASCII-encoded string in lower case representing the media type of thebytesequence.

EachBlobmust have an internalsnapshot state, which must be initially set to the state of the underlying storage, if any such underlying storage exists. Further normative definition ofsnapshot statecan be found forFiles.

[Exposed=(Window,Worker),Serializable]
interfaceBlob{
constructor(optionalsequence<BlobPart>blobParts,
optionalBlobPropertyBagoptions= {});

readonlyattributeunsignedlonglongsize;
readonlyattributeDOMStringtype;

// slice Blob into byte-ranged chunks
Blobslice(optional[Clamp]longlongstart,
optional[Clamp]longlongend,
optionalDOMStringcontentType);

// read from the Blob.
[NewObject]ReadableStreamstream();
[NewObject]Promise<USVString>text();
[NewObject]Promise<ArrayBuffer>arrayBuffer();
[NewObject]Promise<Uint8Array>bytes();
};

enumEndingType{"transparent","native"};

dictionaryBlobPropertyBag{
DOMStringtype= "";
EndingTypeendings= "transparent";
};

typedef(BufferSourceorBloborUSVString)BlobPart;

Blobobjects areserializable objects.Theirserialization steps, givenvalueandserialized,are:

  1. Setserialized.[[SnapshotState]] tovalue’ssnapshot state.

  2. Setserialized.[[ByteSequence]] tovalue’s underlying byte sequence.

Theirdeserialization step,givenserializedandvalue,are:

  1. Setvalue’ssnapshot statetoserialized.[[SnapshotState]].

  2. Setvalue’s underlying byte sequence toserialized.[[ByteSequence]].

ABlobblobhas an associatedget streamalgorithm, which runs these steps:
  1. Letstreambe anewReadableStreamcreated inblob’srelevant Realm.

  2. Set upstreamwith byte reading support.

  3. Run the following stepsin parallel:

    1. While not all bytes ofblobhave been read:

      1. Letbytesbe thebyte sequencethat results from reading achunkfromblob,or failure if a chunk cannot be read.

      2. Queue a global taskon thefile reading task sourcegivenblob’srelevant global objectto perform the following steps:

        1. Ifbytesis failure, thenerrorstreamwith afailure reasonand abort these steps.

        2. Letchunkbe a newUint8Arraywrapping anArrayBuffercontainingbytes.If creating theArrayBufferthrows an exception, thenerrorstreamwith that exception and abort these steps.

        3. Enqueuechunkinstream.

      We need to specify more concretely what reading from a Blob actually does, what possible errors can happen, perhaps something about chunk sizes, etc.

  4. Returnstream.

3.1.Constructors

TheBlob()constructor can be invoked with zero or more parameters. When theBlob()constructor is invoked, user agents must run the following steps:
  1. If invoked with zero parameters, return a newBlobobject consisting of 0 bytes, withsizeset to 0, and withtypeset to the empty string.

  2. Letbytesbe the result ofprocessing blob partsgivenblobPartsandoptions.

  3. If thetypemember of theoptionsargument is not the empty string, run the following sub-steps:

    1. Lettbe thetypedictionary member. Iftcontains any characters outside the range U+0020 to U+007E, then settto the empty string and return from these substeps.

    2. Convert every character inttoASCII lowercase.

  4. Return aBlobobject referring tobytesas its associatedbytesequence, with itssizeset to the length ofbytes, and itstypeset to the value oftfrom the substeps above.

3.1.1.Constructor Parameters

TheBlob()constructor can be invoked with the parameters below:

AblobPartssequence
which takes any number of the following types of elements, and in any order:
AnoptionalBlobPropertyBag
which takes these optional members:
Toprocess blob partsgiven a sequence ofBlobPart'spartsandBlobPropertyBagoptions, run the following steps:
  1. Letbytesbe an empty sequence of bytes.

  2. For eachelementinparts:

    1. Ifelementis aUSVString,run the following substeps:

      1. Letsbeelement.

      2. If theendingsmember ofoptionsis"native", setsto the result ofconverting line endings to nativeofelement.

      3. Append the result ofUTF-8 encodingstobytes.

        Note:The algorithm from WebIDL[WebIDL]replaces unmatched surrogates in an invalid utf-16 string with U+FFFD replacement characters. Scenarios exist when theBlobconstructor may result in some data loss due to lost or scrambled character sequences.

    2. Ifelementis aBufferSource,get a copy of the bytes held by the buffer source,and append those bytes tobytes.

    3. Ifelementis aBlob, append the bytes it represents tobytes.

      Note:Thetypeof theBlobarray element is ignored and will not affecttypeof returnedBlobobject.

  3. Returnbytes.

Toconvert line endings to nativein astrings, run the following steps:
  1. Letnative line endingbe be thecode pointU+000A LF.

  2. If the underlying platform’s conventions are to represent newlines as a carriage return and line feed sequence, setnative line endingto thecode pointU+000D CR followed by thecode pointU+000A LF.

  3. Setresultto the emptystring.

  4. Letpositionbe aposition variablefors, initially pointing at the start ofs.

  5. Lettokenbe the result ofcollecting a sequence of code pointsthat are not equal to U+000A LF or U+000D CR fromsgivenposition.

  6. Appendtokentoresult.

  7. Whilepositionis not past the end ofs:

    1. If thecode pointatpositionwithinsequals U+000D CR:

      1. Appendnative line endingtoresult.

      2. Advancepositionby 1.

      3. Ifpositionis not past the end ofsand thecode pointatpositionwithinsequals U+000A LF advancepositionby 1.

    2. Otherwise if thecode pointatpositionwithinsequals U+000A LF, advancepositionby 1 and appendnative line endingtoresult.

    3. Lettokenbe the result ofcollecting a sequence of code pointsthat are not equal to U+000A LF or U+000D CR fromsgivenposition.

    4. Appendtokentoresult.

  8. Returnresult.

Examples of constructor usage follow.
// Create a new Blob object

vara=newBlob();

// Create a 1024-byte ArrayBuffer
// buffer could also come from reading a File

varbuffer=newArrayBuffer(1024);

// Create ArrayBufferView objects based on buffer

varshorts=newUint16Array(buffer,512,128);
varbytes=newUint8Array(buffer,shorts.byteOffset+shorts.byteLength);

varb=newBlob(["foobarbazetcetc"+"birdiebirdieboo"],{type:"text/plain;charset=utf-8"});

varc=newBlob([b,shorts]);

vara=newBlob([b,c,bytes]);

vard=newBlob([buffer,b,c,bytes]);

3.2.Attributes

size,of typeunsigned long long,readonly
Returns the size of thebytesequence in number of bytes. On getting, conforming user agents must return the total number of bytes that can be read by aFileReaderorFileReaderSyncobject, or 0 if theBlobhas no bytes to be read.
type,of typeDOMString,readonly
The ASCII-encoded string in lower case representing the media type of theBlob. On getting, user agents must return the type of aBlobas an ASCII-encoded string in lower case, such that when it is converted to abytesequence, it is aparsable MIME type, or the empty string – 0 bytes – if the type cannot be determined.

Thetypeattribute can be set by the web application itself through constructor invocation and through theslice()call; in these cases, further normative conditions for this attribute are in§ 3.1 Constructors,§ 4.1 Constructor, and§ 3.3.1 The slice() methodrespectively. User agents can also determine thetypeof aBlob, especially if thebytesequence is from an on-disk file; in this case, further normative conditions are in thefile type guidelines.

Note:The typetof aBlobis considered aparsable MIME type, if performing theparse a MIME typealgorithm to a byte sequence converted from the ASCII-encoded string representing the Blob object’s type does not return failure.

Note:Use of thetypeattribute informs thepackage dataalgorithm and determines theContent-Typeheader whenfetchingblob URLs.

3.3.Methods and Parameters

3.3.1.Theslice()method

Theslice()method returns a newBlobobject with bytes ranging from the optionalstartparameter up to but not including the optionalendparameter, and with atypeattribute that is the value of the optionalcontentTypeparameter. It must act as follows:
  1. LetsliceStart,sliceEnd,andsliceContentTypebe null.

  2. Ifstartis given, setsliceStarttostart.

  3. Ifendis given, setsliceEndtoend.

  4. IfcontentTypeis given, setsliceContentTypetocontentType.

  5. Return the result ofslice blobgiventhis,sliceStart,sliceEnd,andsliceContentType.

The examples below illustrate the different types ofslice()calls possible. Since theFileinterface inherits from theBlobinterface, examples are based on the use of theFileinterface.
// obtain input element through DOM

varfile=document.getElementById('file').files[0];
if(file)
{
// create an identical copy of file
// the two calls below are equivalent

varfileClone=file.slice();
varfileClone2=file.slice(0,file.size);

// slice file into 1/2 chunk starting at middle of file
// Note the use of negative number

varfileChunkFromEnd=file.slice(-(Math.round(file.size/2)));

// slice file into 1/2 chunk starting at beginning of file

varfileChunkFromStart=file.slice(0,Math.round(file.size/2));

// slice file from beginning till 150 bytes before end

varfileNoMetadata=file.slice(0,-150,"application/experimental");
}

3.3.2.Thestream()method

Thestream()method, when invoked, must return the result of callingget streamonthis.

3.3.3.Thetext()method

Thetext()method, when invoked, must run these steps:

  1. Letstreambe the result of callingget streamonthis.

  2. Letreaderbe the result ofgetting a readerfromstream. If that threw an exception, return a new promise rejected with that exception.

  3. Letpromisebe the result ofreading all bytesfromstreamwithreader.

  4. Return the result of transformingpromiseby a fulfillment handler that returns the result of runningUTF-8 decodeon its first argument.

Note:This is different from the behavior ofreadAsText()to align better with the behavior ofFetch’s text().Specifically this method will always use UTF-8 as encoding, whileFileReadercan use a different encoding depending on the blob’s type and passed in encoding name.

3.3.4.ThearrayBuffer()method

ThearrayBuffer()method, when invoked, must run these steps:

  1. Letstreambe the result of callingget streamonthis.

  2. Letreaderbe the result ofgetting a readerfromstream. If that threw an exception, return a new promise rejected with that exception.

  3. Letpromisebe the result ofreading all bytesfromstreamwithreader.

  4. Return the result of transformingpromiseby a fulfillment handler that returns a newArrayBufferwhose contents are its first argument.

3.3.5.Thebytes()method

Thebytes()method, when invoked, must run these steps:

  1. Letstreambe the result of callingget streamonthis.

  2. Letreaderbe the result ofgetting a readerfromstream. If that threw an exception, return a new promise rejected with that exception.

  3. Letpromisebe the result ofreading all bytesfromstreamwithreader.

  4. Return the result of transformingpromiseby a fulfillment handler that returns a newUint8Arraywrapping anArrayBuffercontaining its first argument.

4.The File Interface

AFileobject is aBlobobject with anameattribute, which is a string; it can be created within the web application via a constructor, or is a reference to abytesequence from a file from the underlying (OS) file system.

If aFileobject is a reference to abytesequence originating from a file on disk, then itssnapshot stateshould be set to the state of the file on disk at the time theFileobject is created.

Note:This is a non-trivial requirement to implement for user agents, and is thus not amustbut ashould[RFC2119]. User agents should endeavor to have aFileobject’ssnapshot stateset to the state of the underlying storage on disk at the time the reference is taken. If the file is modified on disk following the time a reference has been taken, theFile'ssnapshot statewill differ from the state of the underlying storage. User agents may use modification time stamps and other mechanisms to maintainsnapshot state, but this is left as an implementation detail.

When aFileobject refers to a file on disk, user agents must return thetypeof that file, and must follow thefile type guidelinesbelow:

[Exposed=(Window,Worker),Serializable]
interfaceFile:Blob{
constructor(sequence<BlobPart>fileBits,
USVStringfileName,
optionalFilePropertyBagoptions= {});
readonlyattributeDOMStringname;
readonlyattributelonglonglastModified;
};

dictionaryFilePropertyBag:BlobPropertyBag{
longlonglastModified;
};

Fileobjects areserializable objects.Theirserialization steps, givenvalueandserialized,are:

  1. Setserialized.[[SnapshotState]] tovalue’ssnapshot state.

  2. Setserialized.[[ByteSequence]] tovalue’s underlying byte sequence.

  3. Setserialized.[[Name]] to the value ofvalue’snameattribute.

  4. Setserialized.[[LastModified]] to the value ofvalue’slastModifiedattribute.

Theirdeserialization steps,givenvalueandserialized,are:

  1. Setvalue’ssnapshot statetoserialized.[[SnapshotState]].

  2. Setvalue’s underlying byte sequence toserialized.[[ByteSequence]].

  3. Initialize the value ofvalue’snameattribute toserialized.[[Name]].

  4. Initialize the value ofvalue’slastModifiedattribute toserialized.[[LastModified]].

4.1.Constructor

TheFileconstructor is invoked with two or three parameters, depending on whether the optional dictionary parameter is used. When theFile()constructor is invoked, user agents must run the following steps:
  1. Letbytesbe the result ofprocessing blob partsgivenfileBitsandoptions.

  2. Letnbe thefileNameargument to the constructor.

    Note:Underlying OS filesystems use differing conventions for file name; with constructed files, mandating UTF-16 lessens ambiquity when file names are converted tobytesequences.

  3. ProcessFilePropertyBagdictionary argument by running the following substeps:

    1. If thetypemember is provided and is not the empty string, lettbe set to thetypedictionary member. Iftcontains any characters outside the range U+0020 to U+007E, then settto the empty string and return from these substeps.

    2. Convert every character inttoASCII lowercase.

    3. If thelastModifiedmember is provided, letdbe set to thelastModifieddictionary member. If it is not provided, setdto the current date and time represented as the number of milliseconds since theUnix Epoch(which is the equivalent ofDate.now()[ECMA-262]).

      Note:Since ECMA-262Dateobjects convert tolong longvalues representing the number of milliseconds since theUnix Epoch, thelastModifiedmember could be aDateobject[ECMA-262].

  4. Return a newFileobjectFsuch that:

    1. Frefers to thebytesbytesequence.

    2. F.sizeis set to the number of total bytes inbytes.

    3. F.nameis set ton.

    4. F.typeis set tot.

    5. F.lastModifiedis set tod.

4.1.1.Constructor Parameters

TheFile()constructor can be invoked with the parameters below:

AfileBitssequence
which takes any number of the following elements, and in any order:
AfileNameparameter
AUSVStringparameter representing the name of the file; normative conditions for this constructor parameter can be found in§ 4.1 Constructor.
An optionalFilePropertyBagdictionary
which in addition to themembersofBlobPropertyBagtakes one member:
  • An optionallastModifiedmember, which must be along long; normative conditions for this member are provided in§ 4.1 Constructor.

4.2.Attributes

name,of typeDOMString,readonly
The name of the file. On getting, this must return the name of the file as a string. There are numerous file name variations and conventions used by different underlying OS file systems; this is merely the name of the file, without path information. On getting, if user agents cannot make this information available, they must return the empty string. If aFileobject is created using a constructor, further normative conditions for this attribute are found in§ 4.1 Constructor.
lastModified,of typelong long,readonly
The last modified date of the file. On getting, if user agents can make this information available, this must return along longset to the time the file was last modified as the number of milliseconds since theUnix Epoch. If the last modification date and time are not known, the attribute must return the current date and time as along longrepresenting the number of milliseconds since theUnix Epoch; this is equivalent toDate.now()[ECMA-262]. If aFileobject is created using a constructor, further normative conditions for this attribute are found in§ 4.1 Constructor.

TheFileinterface is available on objects that expose an attribute of typeFileList; these objects are defined in HTML[HTML]. TheFileinterface, which inherits fromBlob,is immutable, and thus represents file data that can be read into memory at the time aread operationis initiated. User agents must process reads on files that no longer exist at the time of read aserrors, throwing aNotFoundErrorexception if using aFileReaderSyncon a Web Worker[Workers]or firing anerrorevent with theerrorattribute returning aNotFoundError.

In the examples below, metadata from a file object is displayed meaningfully, and a file object is created with a name and a last modified date.
varfile=document.getElementById("filePicker").files[0];
vardate=newDate(file.lastModified);
println("You selected the file"+file.name+"which was modified on"+date.toDateString()+".");

...

// Generate a file with a specific last modified date

vard=newDate(2013,12,5,16,23,45,600);
vargeneratedFile=newFile(["Rough Draft...."],"Draft1.txt",{type:"text/plain",lastModified:d})

...

5.The FileList Interface

Note:TheFileListinterface should be considered "at risk" since the general trend on the Web Platform is to replace such interfaces with theArrayplatform object in ECMAScript[ECMA-262]. In particular, this means syntax of the sortfilelist.item(0)is at risk; most other programmatic use ofFileListis unlikely to be affected by the eventual migration to anArraytype.

This interface is a list ofFileobjects.

[Exposed=(Window,Worker),Serializable]
interfaceFileList{
getterFile?item(unsignedlongindex);
readonlyattributeunsignedlonglength;
};

FileListobjects areserializable objects.Theirserialization steps, givenvalueandserialized,are:

  1. Setserialized.[[Files]] to an emptylist.

  2. For eachfileinvalue,append thesub-serializationoffiletoserialized.[[Files]].

Theirdeserialization step,givenserializedandvalue,are:

  1. For eachfileofserialized.[[Files]], add thesub-deserializationoffiletovalue.

Sample usage typically involves DOM access to the<input type= "file" >element within a form, and then accessing selected files.
// uploadData is a form element
// fileChooser is input element of type 'file'
varfile=document.forms['uploadData']['fileChooser'].files[0];

// alternative syntax can be
// var file = document.forms['uploadData']['fileChooser'].files.item(0);

if(file)
{
// Perform file ops
}

5.1.Attributes

length,of typeunsigned long,readonly
must return the number of files in theFileListobject. If there are no files, this attribute must return 0.

5.2.Methods and Parameters

item(index)
must return theindexthFileobject in theFileList. If there is noindexthFileobject in theFileList, then this method must returnnull.

indexmust be treated by user agents as value for the position of aFileobject in theFileList, with 0 representing the first file.Supported property indicesare the numbers in the range zero to one less than the number ofFileobjects represented by theFileListobject. If there are no suchFileobjects, then there are no supported property indices.

Note:TheHTMLInputElementinterface has a readonly attribute of typeFileList, which is what is being accessed in the above example. Other interfaces with a readonly attribute of typeFileListinclude theDataTransferinterface.

6.Reading Data

6.1.The File Reading Task Source

This specification defines a new generictask sourcecalled thefile reading task source, which is used for alltasks that are queuedin this specification to read byte sequences associated withBlobandFileobjects. It is to be used for features that trigger in response to asynchronously reading binary data.

6.2.TheFileReaderAPI

[Exposed=(Window,Worker)]
interfaceFileReader:EventTarget{
constructor();
// async read methods
undefinedreadAsArrayBuffer(Blobblob);
undefinedreadAsBinaryString(Blobblob);
undefinedreadAsText(Blobblob,optionalDOMStringencoding);
undefinedreadAsDataURL(Blobblob);

undefinedabort();

// states
constunsignedshortEMPTY= 0;
constunsignedshortLOADING= 1;
constunsignedshortDONE= 2;

readonlyattributeunsignedshortreadyState;

// File or Blob data
readonlyattribute(DOMStringorArrayBuffer)?result;

readonlyattributeDOMException?error;

// event handler content attributes
attributeEventHandleronloadstart;
attributeEventHandleronprogress;
attributeEventHandleronload;
attributeEventHandleronabort;
attributeEventHandleronerror;
attributeEventHandleronloadend;
};

AFileReaderhas an associatedstate, that is"empty","loading",or"done".It is initially"empty".

AFileReaderhas an associatedresult(null,aDOMStringor anArrayBuffer). It is initiallynull.

AFileReaderhas an associatederror(nullor aDOMException). It is initiallynull.

TheFileReader()constructor, when invoked, must return a newFileReaderobject.

ThereadyStateattribute’s getter, when invoked, switches onthis'sstateand runs the associated step:

"empty"

ReturnEMPTY

"loading"

ReturnLOADING

"done"

ReturnDONE

Theresultattribute’s getter, when invoked, must returnthis'sresult.

Theerrorattribute’s getter, when invoked, must returnthis'serror.

AFileReaderfrhas an associatedread operationalgorithm, which givenblob,atypeand an optionalencodingName, runs the following steps:
  1. Iffr’sstateis"loading", throw anInvalidStateErrorDOMException.

  2. Setfr’sstateto"loading".

  3. Setfr’sresulttonull.

  4. Setfr’serrortonull.

  5. Letstreambe the result of callingget streamonblob.

  6. Letreaderbe the result ofgetting a readerfromstream.

  7. Letbytesbe an emptybyte sequence.

  8. LetchunkPromisebe the result ofreading a chunkfromstreamwithreader.

  9. LetisFirstChunkbe true.

  10. In parallel,while true:

    1. Wait forchunkPromiseto be fulfilled or rejected.

    2. IfchunkPromiseis fulfilled, andisFirstChunkis true,queue a tasktofire a progress eventcalledloadstartatfr.

      We might changeloadstartto be dispatched synchronously, to align with XMLHttpRequest behavior.[Issue #119]

    3. SetisFirstChunkto false.

    4. IfchunkPromiseis fulfilled with an object whosedoneproperty is false and whosevalueproperty is aUint8Arrayobject, run these steps:

      1. Letbsbe thebyte sequencerepresented by theUint8Arrayobject.

      2. Appendbstobytes.

      3. If roughly 50ms have passed since these steps were last invoked,queue a tasktofire a progress eventcalledprogressatfr.

      4. SetchunkPromiseto the result ofreading a chunkfromstreamwithreader.

    5. Otherwise, ifchunkPromiseis fulfilled with an object whosedoneproperty is true,queue a taskto run the following steps and abort this algorithm:

      1. Setfr’sstateto"done".

      2. Letresultbe the result ofpackage datagivenbytes,type,blob’stype,andencodingName.

      3. Ifpackage datathrew an exceptionerror:

        1. Setfr’serrortoerror.

        2. Fire a progress eventcallederroratfr.

      4. Else:

        1. Setfr’sresulttoresult.

        2. Fire a progress eventcalledloadat thefr.

      5. Iffr’sstateis not"loading",fire a progress eventcalledloadendat thefr.

        Note:Event handler for theloadorerrorevents could have started another load, if that happens theloadendevent for this load is not fired.

    6. Otherwise, ifchunkPromiseis rejected with an errorerror,queue a taskto run the following steps and abort this algorithm:

      1. Setfr’sstateto"done".

      2. Setfr’serrortoerror.

      3. Fire a progress eventcallederroratfr.

      4. Iffr’sstateis not"loading",fire a progress eventcalledloadendatfr.

        Note:Event handler for theerrorevent could have started another load, if that happens theloadendevent for this load is not fired.

Use thefile reading task sourcefor all these tasks.

6.2.1.Event Handler Content Attributes

The following are theevent handler content attributes(and their correspondingevent handler event types) that user agents must support onFileReaderas DOM attributes:

event handler content attribute event handler event type
onloadstart loadstart
onprogress progress
onabort abort
onerror error
onload load
onloadend loadend

6.2.2.FileReader States

TheFileReaderobject can be in one of 3 states. ThereadyStateattribute tells you in which state the object is:
EMPTY(numeric value 0)

TheFileReaderobject has been constructed, and there are no pending reads. None of theread methodshave been called. This is the default state of a newly mintedFileReaderobject, until one of theread methodshave been called on it.

LOADING(numeric value 1)

AFileorBlobis being read. One of theread methodsis being processed, and no error has occurred during the read.

DONE(numeric value 2)

The entireFileorBlobhas been read into memory, OR afile read erroroccurred, OR the read was aborted usingabort(). TheFileReaderis no longer reading aFileorBlob. IfreadyStateis set toDONEit means at least one of theread methodshave been called on thisFileReader.

6.2.3.Reading a File or Blob

TheFileReaderinterface makes available severalasynchronous read methodsreadAsArrayBuffer(),readAsBinaryString(),readAsText()andreadAsDataURL(), which read files into memory.

Note:If multiple concurrent read methods are called on the sameFileReaderobject, user agents throw anInvalidStateErroron any of the read methods that occur whenreadyState=LOADING.

(FileReaderSyncmakes available severalsynchronous read methods. Collectively, the sync and async read methods ofFileReaderandFileReaderSyncare referred to as justread methods.)

6.2.3.1.ThereadAsDataURL()method

ThereadAsDataURL(blob)method, when invoked, must initiate aread operationforblobwithDataURL.

6.2.3.2.ThereadAsText()method

ThereadAsText(blob,encoding)method, when invoked, must initiate aread operationforblobwithTextandencoding.

6.2.3.3.ThereadAsArrayBuffer()

ThereadAsArrayBuffer(blob)method, when invoked, must initiate aread operationforblobwithArrayBuffer.

6.2.3.4.ThereadAsBinaryString()method

ThereadAsBinaryString(blob)method, when invoked, must initiate aread operationforblobwithBinaryString.

Note:The use ofreadAsArrayBuffer()is preferred overreadAsBinaryString(),which is provided for backwards compatibility.

6.2.3.5.Theabort()method

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

  1. Ifthis'sstateis"empty"or ifthis'sstateis"done"setthis'sresulttonullandterminate this algorithm.

  2. Ifthis'sstateis"loading"setthis'sstateto"done"and setthis'sresulttonull.

  3. If there are anytasksfromthison thefile reading task sourcein an affiliatedtask queue, then remove thosetasksfrom that task queue.

  4. Terminate the algorithmfor theread methodbeing processed.

  5. Fire a progress eventcalledabortatthis.

  6. Ifthis'sstateis not"loading",fire a progress eventcalledloadendatthis.

6.3.Packaging data

ABlobhas an associatedpackage dataalgorithm, givenbytes,atype,a optionalmimeType,and a optionalencodingName, which switches ontypeand runs the associated steps:
DataURL

Returnbytesas a DataURL[RFC2397]subject to the considerations below:

  • UsemimeTypeas part of the Data URL if it is available in keeping with the Data URL specification[RFC2397].

  • IfmimeTypeis not available return a Data URL without a media-type.[RFC2397].

Better specify how the DataURL is generated.[Issue #104]

Text
  1. Letencodingbe failure.

  2. If theencodingNameis present, setencodingto the result ofgetting an encodingfromencodingName.

  3. Ifencodingis failure, andmimeTypeis present:

    1. Lettypebe the result ofparse a MIME typegivenmimeType.

    2. Iftypeis not failure, setencodingto the result ofgetting an encodingfromtype’sparameters["charset"].

      Ifblobhas atypeattribute oftext/plain;charset=utf-8thengetting an encodingis run using"utf-8"as the label. Note that user agents must parse and extract the portion of the Charset Parameter that constitutes alabelof an encoding.
  4. Ifencodingis failure, then setencodingtoUTF-8.

  5. Decodebytesusing fallback encodingencoding,and return the result.

ArrayBuffer

Return a newArrayBufferwhose contents arebytes.

BinaryString

Returnbytesas a binary string, in which every byte is represented by a code unit of equal value [0..255].

6.4.Events

TheFileReaderobject must be the event target for all events in this specification.

When this specification says tofire a progress eventcalled e(for someProgressEventeat a givenFileReaderreader), the following are normative:

6.4.1.Event Summary

The following are the events that arefiredatFileReaderobjects.

Event name Interface Fired when…
loadstart ProgressEvent When the read starts.
progress ProgressEvent While reading (and decoding)blob
abort ProgressEvent When the read has been aborted. For instance, by invoking theabort()method.
error ProgressEvent When the read has failed (seefile read errors).
load ProgressEvent When the read has successfully completed.
loadend ProgressEvent When the request has completed (either in success or failure).

6.4.2.Summary of Event Invariants

This section is informative.

The following are invariants applicable toevent firingfor a given asynchronousread methodin this specification:

  1. Once aloadstarthas been fired, a correspondingloadendfires at completion of the read, UNLESS any of the following are true:

    • theread methodhas been cancelled usingabort()and a newread methodhas been invoked

    • the event handler function for aloadevent initiates a new read

    • the event handler function for aerrorevent initiates a new read.

    Note:The eventsloadstartandloadendare not coupled in a one-to-one manner.

    This example showcases "read-chaining": initiating another read from within an event handler while the "first" read continues processing.
    // In code of the sort...
    reader.readAsText(file);
    reader.onload=function(){reader.readAsText(alternateFile);}
    
    .....
    
    //... the loadend event must not fire for the first read
    
    reader.readAsText(file);
    reader.abort();
    reader.onabort=function(){reader.readAsText(updatedFile);}
    
    //... the loadend event must not fire for the first read
    
  2. Oneprogressevent will fire whenblobhas been completely read into memory.

  3. Noprogressevent fires beforeloadstart.

  4. Noprogressevent fires after any one ofabort,load,anderrorhave fired. At most one ofabort,load,anderrorfire for a given read.

  5. Noabort,load,orerrorevent fires afterloadend.

6.5.Reading on Threads

Web Workers allow for the use of synchronousFileorBlobread APIs, since such reads on threads do not block the main thread. This section defines a synchronous API, which can be used within Workers [[Web Workers]]. Workers can avail of both the asynchronous API (theFileReaderobject)andthe synchronous API (theFileReaderSyncobject).

6.5.1.TheFileReaderSyncAPI

This interface provides methods tosynchronously readFileorBlobobjects into memory.

[Exposed=(DedicatedWorker,SharedWorker)]
interfaceFileReaderSync{
constructor();
// Synchronously return strings

ArrayBufferreadAsArrayBuffer(Blobblob);
DOMStringreadAsBinaryString(Blobblob);
DOMStringreadAsText(Blobblob,optionalDOMStringencoding);
DOMStringreadAsDataURL(Blobblob);
};
6.5.1.1.Constructors

When theFileReaderSync()constructor is invoked, the user agent must return a newFileReaderSyncobject.

6.5.1.2.ThereadAsText()

ThereadAsText(blob,encoding)method, when invoked, must run these steps:

  1. Letstreambe the result of callingget streamonblob.

  2. Letreaderbe the result ofgetting a readerfromstream.

  3. Letpromisebe the result ofreading all bytesfromstreamwithreader.

  4. Wait forpromiseto be fulfilled or rejected.

  5. Ifpromisefulfilled with abyte sequencebytes:

    1. Return the result ofpackage datagivenbytes,Text,blob’stype,andencoding.

  6. Throwpromise’s rejection reason.

6.5.1.3.ThereadAsDataURL()method

ThereadAsDataURL(blob)method, when invoked, must run these steps:

  1. Letstreambe the result of callingget streamonblob.

  2. Letreaderbe the result ofgetting a readerfromstream.

  3. Letpromisebe the result ofreading all bytesfromstreamwithreader.

  4. Wait forpromiseto be fulfilled or rejected.

  5. Ifpromisefulfilled with abyte sequencebytes:

    1. Return the result ofpackage datagivenbytes,DataURL,andblob’stype.

  6. Throwpromise’s rejection reason.

6.5.1.4.ThereadAsArrayBuffer()method

ThereadAsArrayBuffer(blob)method, when invoked, must run these steps:

  1. Letstreambe the result of callingget streamonblob.

  2. Letreaderbe the result ofgetting a readerfromstream.

  3. Letpromisebe the result ofreading all bytesfromstreamwithreader.

  4. Wait forpromiseto be fulfilled or rejected.

  5. Ifpromisefulfilled with abyte sequencebytes:

    1. Return the result ofpackage datagivenbytes,ArrayBuffer,andblob’stype.

  6. Throwpromise’s rejection reason.

6.5.1.5.ThereadAsBinaryString()method

ThereadAsBinaryString(blob)method, when invoked, must run these steps:

  1. Letstreambe the result of callingget streamonblob.

  2. Letreaderbe the result ofgetting a readerfromstream.

  3. Letpromisebe the result ofreading all bytesfromstreamwithreader.

  4. Wait forpromiseto be fulfilled or rejected.

  5. Ifpromisefulfilled with abyte sequencebytes:

    1. Return the result ofpackage datagivenbytes,BinaryString,andblob’stype.

  6. Throwpromise’s rejection reason.

Note:The use ofreadAsArrayBuffer()is preferred overreadAsBinaryString(),which is provided for backwards compatibility.

7.Errors and Exceptions

File read errorscan occur when reading files from the underlying filesystem. The list below of potential error conditions isinformative.

7.1.Throwing an Exception or Returning an Error

This section is normative.

Error conditions can arise when reading aFileor aBlob.

Theread operationcan terminate due to error conditions when reading aFileor aBlob; the particular error condition that causes theget streamalgorithm to fail is called afailure reason.Afailure reasonis one ofNotFound,UnsafeFile,TooManyReads,SnapshotState,orFileLock.

Synchronous read methodsthrowexceptions of the type in the table below if there has been an error owing to a particularfailure reason.

Asynchronous read methods use theerrorattribute of theFileReaderobject, which must return aDOMExceptionobject of the most appropriate type from the table below if there has been an error owing to a particularfailure reason, or otherwise return null.

Type Description and Failure Reason
NotFoundError If theFileorBlobresource could not be found at the time the read was processed, this is theNotFoundfailure reason.

For asynchronous read methods theerrorattribute must return aNotFoundErrorexception and synchronous read methods mustthrowaNotFoundErrorexception.

SecurityError If:
  • it is determined that certain files are unsafe for access within a Web application, this is theUnsafeFilefailure reason.

  • it is determined that too many read calls are being made onFileorBlobresources, this is theTooManyReadsfailure reason.

For asynchronous read methods theerrorattribute may return aSecurityErrorexception and synchronous read methods maythrowaSecurityErrorexception.

This is a security error to be used in situations not covered by any otherfailure reason.

NotReadableError If:
  • thesnapshot stateof aFileor aBlobdoes not match the state of the underlying storage, this is theSnapshotStatefailure reason.

  • theFileorBlobcannot be read, typically due due to permission problems that occur after asnapshot statehas been established (e.g. concurrent lock on the underlying storage with another application) then this is theFileLockfailure reason.

For asynchronous read methods theerrorattribute must return aNotReadableErrorexception and synchronous read methods mustthrowaNotReadableErrorexception.

8.A URL for Blob and MediaSource reference

This section defines aschemefor aURLused to refer toBlobandMediaSourceobjects.

8.1.Introduction

This section is informative.

Blob (or object) URLsare URLs likeblob:http://example.com/550e8400-e29b-41d4-a716-446655440000. This enables integration ofBlobs andMediaSources with other APIs that are only designed to be used with URLs, such as theimgelement.Blob URLscan also be used to navigate to as well as to trigger downloads of locally generated data.

For this purpose two static methods are exposed on theURLinterface,createObjectURL(obj)andrevokeObjectURL(url). The first method creates a mapping from aURLto aBlob, and the second method revokes said mapping. As long as the mapping exist theBlobcan’t be garbage collected, so some care must be taken to revoke the URL as soon as the reference is no longer needed. All URLs are revoked when the global that created the URL itself goes away.

8.2.Model

Each user agent must maintain ablob URL store. Ablob URL storeis amapwherekeysarevalid URL stringsandvaluesareblob URL Entries.

Ablob URL entryconsists of anobject(of typeBloborMediaSource), and anenvironment(anenvironment settings object).

Keysin theblob URL store(also known asblob URLs) arevalid URL stringsthat whenparsedresult in aURLwith aschemeequal to "blob", anempty host,and apathconsisting of one element itself also avalid URL string.

Togenerate a new blob URL,run the following steps:
  1. Letresultbe the empty string.

  2. Append the string "blob:"toresult.

  3. Letsettingsbe thecurrent settings object

  4. Letoriginbesettings’sorigin.

  5. Letserializedbe theASCII serializationoforigin.

  6. Ifserializedis "null",set it to an implementation-defined value.

  7. Appendserializedtoresult.

  8. Append U+0024 SOLIDUS (/) toresult.

  9. Generate a UUID[RFC4122]as a string and append it toresult.

  10. Returnresult.

An example of a blob URL that can be generated by this algorithm isblob:https://example.org/40a5fb5a-d56d-4a33-b4e2-0acf6a8e5f64.
Toadd an entry to the blob URL storefor a givenobject, run the following steps:
  1. Letstorebe the user agent’sblob URL store.

  2. Leturlbe the result ofgenerating a new blob URL.

  3. Letentrybe a newblob URL entryconsisting ofobjectand thecurrent settings object.

  4. Setstore[url] toentry.

  5. Returnurl.

Toremove an entry from the blob URL storefor a givenurl, run the following steps:
  1. Letstorebe the user agent’sblob URL store;

  2. Leturl stringbe the result ofserializingurl.

  3. Removestore[url string].

8.3.Dereferencing Model for blob URLs

Toresolve a blob URLgiven aURLurl:
  1. Assert:url’sschemeis "blob".

  2. Letstorebe the user agent’sblob URL store.

  3. Leturl stringbe the result ofserializingurlwith theexclude fragment flagset.

  4. Ifstore[url string]exists,returnstore[url string]; otherwise return failure.

Futher requirements for the parsing and fetching model forblob URLsare defined in the[URL]and[Fetch]specifications.

8.3.1.Origin of blob URLs

This section is informative.

The origin of a blob URL is always the same as that of the environment that created the URL, as long as the URL hasn’t been revoked yet. This is achieved by the[URL]spec looking up the URL in theblob URL storewhen parsing a URL, and using that entry to return the correct origin.

If the URL was revoked the serialization of the origin will still remain the same as the serialization of the origin of the environment that created the blob URL, but for opaque origins the origin itself might be distinct. This difference isn’t observable though, since a revoked blob URL can’t be resolved/fetched anymore anyway.

8.3.2.Lifetime of blob URLs

This specification extends theunloading document cleanup stepswith the following steps:

  1. Letenvironmentbe theDocument'srelevant settings object.

  2. Letstorebe the user agent’sblob URL store;

  3. Remove fromstoreany entries for which thevalue'senvironmentis equal toenvironment.

This needs a similar hook when a worker is unloaded.

8.4.Creating and Revoking a blob URL

Blob URLsare created and revoked using static methods exposed on theURLobject. Revocation of ablob URLdecouples theblob URLfrom the resource it refers to, and if it is dereferenced after it is revoked, user agents must act as if anetwork errorhas occurred. This section describes a supplemental interface to the URL specification[URL]and presents methods forblob URLcreation and revocation.

[Exposed=(Window,DedicatedWorker,SharedWorker)]
partialinterfaceURL{
staticDOMStringcreateObjectURL((BloborMediaSource)obj);
staticundefinedrevokeObjectURL(DOMStringurl);
};
ThecreateObjectURL(obj)static method must return the result ofadding an entry to the blob URL storeforobj.
TherevokeObjectURL(url)static method must run these steps:
  1. Leturl recordbe the result ofparsingurl.

  2. Ifurl record’sschemeis not "blob",return.

  3. Letoriginbe theoriginofurl record.

  4. Letsettingsbe thecurrent settings object.

  5. Iforiginis notsame originwithsettings’sorigin,return.

  6. Remove an entry from the Blob URL Storeforurl.

Note:This means that rather than throwing some kind of error, attempting to revoke a URL that isn’t registered will silently fail. User agents might display a message on the error console if this happens.

Note:Attempts to dereferenceurlafter it has been revoked will result in anetwork error. Requests that were started before theurlwas revoked should still succeed.

In the example below,window1andwindow2are separate, but in thesame origin;window2could be aniframeinsidewindow1.
myurl=window1.URL.createObjectURL(myblob);
window2.URL.revokeObjectURL(myurl);

Since a user agent has one globalblob URL store, it is possible to revoke an object URL from a different window than from which it was created. TheURL.revokeObjectURL()call ensures that subsequent dereferencing ofmyurlresults in a the user agent acting as if anetwork errorhas occurred.

8.4.1.Examples of blob URL Creation and Revocation

Blob URLs are strings that are used tofetchBlobobjects, and can persist for as long as thedocumentfrom which they were minted usingURL.createObjectURL()see§ 8.3.2 Lifetime of blob URLs.

This section gives sample usage of creation and revocation ofblob URLs with explanations.

In the example below, twoimgelements[HTML]refer to the sameblob URL:
url=URL.createObjectURL(blob);
img1.src=url;
img2.src=url;
In the example below,URL.revokeObjectURL()is explicitly called.
varblobURLref=URL.createObjectURL(file);
img1=newImage();
img2=newImage();

// Both assignments below work as expected
img1.src=blobURLref;
img2.src=blobURLref;

//... Following body load
// Check if both images have loaded
if(img1.complete&&img2.complete){
// Ensure that subsequent refs throw an exception
URL.revokeObjectURL(blobURLref);
}else{
msg("Images cannot be previewed!");
// revoke the string-based reference
URL.revokeObjectURL(blobURLref);
}

The example above allows multiple references to a singleblob URL, and the web developer then revokes theblob URLstring after both image objects have been loaded. While not restricting number of uses of theblob URLoffers more flexibility, it increases the likelihood of leaks; developers should pair it with a corresponding call toURL.revokeObjectURL().

9.Security and Privacy Considerations

This section is informative.

This specification allows web content to read files from the underlying file system, as well as provides a means for files to be accessed by unique identifiers, and as such is subject to some security considerations. This specification also assumes that the primary user interaction is with the<input type= "file" />element of HTML forms[HTML], and that all files that are being read byFileReaderobjects have first been selected by the user. Important security considerations include preventing malicious file selection attacks (selection looping), preventing access to system-sensitive files, and guarding against modifications of files on disk after a selection has taken place.

Preventing selection looping

During file selection, a user may be bombarded with the file picker associated with<input type= "file" />(in a "must choose" loop that forces selection before the file picker is dismissed) and a user agent may prevent file access to any selections by making theFileListobject returned be of size 0.

System-sensitive files

(e.g. files in /usr/bin, password files, and other native operating system executables) typically should not be exposed to web content, and should not be accessed viablob URLs. User agents maythrowaSecurityErrorexception for synchronous read methods, or return aSecurityErrorexception for asynchronous reads.

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

10.Requirements and Use Cases

This section covers what the requirements are for this API, as well as illustrates some use cases. This version of the API does not satisfy all use cases; subsequent versions may elect to address these.

Acknowledgements

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

Thanks to Robin Berjon, Jonas Sicking and Vsevolod Shmyroff for editing the original specification.

Special thanks to Olli Pettay, Nikunj Mehta, Garrett Smith, Aaron Boodman, Michael Nordman, Jian Li, Dmitry Titov, Ian Hickson, Darin Fisher, Sam Weinig, Adrian Bateman and Julian Reschke.

Thanks to the W3C WebApps WG, and to participants on the [email protected] listserv

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes.[RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text withclass= "example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text withclass= "note", like this:

Note, this is an informative note.

Conformant Algorithms

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps" ) are to be interpreted with the meaning of the key word ( "must", "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[DOM]
Anne van Kesteren.DOM Standard.Living Standard. URL:https://dom.spec.whatwg.org/
[ECMA-262]
ECMAScript Language Specification.URL:https://tc39.es/ecma262/multipage/
[ENCODING]
Anne van Kesteren.Encoding Standard.Living Standard. URL:https://encoding.spec.whatwg.org/
[Fetch]
Anne van Kesteren.Fetch Standard.Living Standard. URL:https://fetch.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al.HTML Standard.Living Standard. URL:https://html.spec.whatwg.org/multipage/
[INFRA]
Anne van Kesteren; Domenic Denicola.Infra Standard.Living Standard. URL:https://infra.spec.whatwg.org/
[MEDIA-SOURCE-2]
Jean-Yves Avenard; Mark Watson.Media Source Extensions™.URL:https://w3c.github.io/media-source/
[MIMESNIFF]
Gordon P. Hemsley.MIME Sniffing Standard.Living Standard. URL:https://mimesniff.spec.whatwg.org/
[RFC2119]
S. Bradner.Key words for use in RFCs to Indicate Requirement Levels.March 1997. Best Current Practice. URL:https://datatracker.ietf.org/doc/html/rfc2119
[RFC2397]
L. Masinter.The "data" URL scheme.August 1998. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc2397
[RFC4122]
K. Davis; B. Peabody; P. Leach.Universally Unique IDentifiers (UUIDs).May 2024. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc9562
[STREAMS]
Adam Rice; et al.Streams Standard.Living Standard. URL:https://streams.spec.whatwg.org/
[URL]
Anne van Kesteren.URL Standard.Living Standard. URL:https://url.spec.whatwg.org/
[WebIDL]
Edgar Chen; Timothy Gu.Web IDL Standard.Living Standard. URL:https://webidl.spec.whatwg.org/
[XHR]
Anne van Kesteren.XMLHttpRequest Standard.Living Standard. URL:https://xhr.spec.whatwg.org/

Informative References

[Workers]
Ian Hickson.Web Workers.URL:https://html.spec.whatwg.org/multipage/workers.html

IDL Index

[Exposed=(Window,Worker),Serializable]
interfaceBlob{
constructor(optionalsequence<BlobPart>blobParts,
optionalBlobPropertyBagoptions= {});

readonlyattributeunsignedlonglongsize;
readonlyattributeDOMStringtype;

// slice Blob into byte-ranged chunks
Blobslice(optional[Clamp]longlongstart,
optional[Clamp]longlongend,
optionalDOMStringcontentType);

// read from the Blob.
[NewObject]ReadableStreamstream();
[NewObject]Promise<USVString>text();
[NewObject]Promise<ArrayBuffer>arrayBuffer();
[NewObject]Promise<Uint8Array>bytes();
};

enumEndingType{"transparent","native"};

dictionaryBlobPropertyBag{
DOMStringtype= "";
EndingTypeendings= "transparent";
};

typedef(BufferSourceorBloborUSVString)BlobPart;

[Exposed=(Window,Worker),Serializable]
interfaceFile:Blob{
constructor(sequence<BlobPart>fileBits,
USVStringfileName,
optionalFilePropertyBagoptions= {});
readonlyattributeDOMStringname;
readonlyattributelonglonglastModified;
};

dictionaryFilePropertyBag:BlobPropertyBag{
longlonglastModified;
};

[Exposed=(Window,Worker),Serializable]
interfaceFileList{
getterFile?item(unsignedlongindex);
readonlyattributeunsignedlonglength;
};

[Exposed=(Window,Worker)]
interfaceFileReader:EventTarget{
constructor();
// async read methods
undefinedreadAsArrayBuffer(Blobblob);
undefinedreadAsBinaryString(Blobblob);
undefinedreadAsText(Blobblob,optionalDOMStringencoding);
undefinedreadAsDataURL(Blobblob);

undefinedabort();

// states
constunsignedshortEMPTY= 0;
constunsignedshortLOADING= 1;
constunsignedshortDONE= 2;

readonlyattributeunsignedshortreadyState;

// File or Blob data
readonlyattribute(DOMStringorArrayBuffer)?result;

readonlyattributeDOMException?error;

// event handler content attributes
attributeEventHandleronloadstart;
attributeEventHandleronprogress;
attributeEventHandleronload;
attributeEventHandleronabort;
attributeEventHandleronerror;
attributeEventHandleronloadend;
};

[Exposed=(DedicatedWorker,SharedWorker)]
interfaceFileReaderSync{
constructor();
// Synchronously return strings

ArrayBufferreadAsArrayBuffer(Blobblob);
DOMStringreadAsBinaryString(Blobblob);
DOMStringreadAsText(Blobblob,optionalDOMStringencoding);
DOMStringreadAsDataURL(Blobblob);
};

[Exposed=(Window,DedicatedWorker,SharedWorker)]
partialinterfaceURL{
staticDOMStringcreateObjectURL((BloborMediaSource)obj);
staticundefinedrevokeObjectURL(DOMStringurl);
};

Issues Index

We need to specify more concretely what reading from a Blob actually does, what possible errors can happen, perhaps something about chunk sizes, etc.
We might changeloadstartto be dispatched synchronously, to align with XMLHttpRequest behavior.[Issue #119]
Better specify how the DataURL is generated.[Issue #104]
This needs a similar hook when a worker is unloaded.
This section is provisional; more security data may supplement this in subsequent drafts.
MDN

Blob/Blob

In all current engines.

Firefox13+Safari6+Chrome20+
Opera12+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12+
Node.js15.7.0+
MDN

Blob/arrayBuffer

In all current engines.

Firefox69+Safari14+Chrome76+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
Node.js15.7.0+
MDN

Blob/size

In all current engines.

Firefox4+Safari6+Chrome5+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile11+
Node.js15.7.0+
MDN

Blob/slice

In all current engines.

Firefox13+Safari7+Chrome21+
Opera12+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12+
Node.js15.7.0+
MDN

Blob/stream

In all current engines.

Firefox69+Safari14.1+Chrome76+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
Node.js15.7.0+
MDN

Blob/text

In all current engines.

Firefox69+Safari14+Chrome76+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
Node.js15.7.0+
MDN

Blob/type

In all current engines.

Firefox4+Safari6+Chrome5+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile11+
Node.js15.7.0+

File/type

In all current engines.

Firefox3.6+Safari8+Chrome13+
Opera15+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile14+
MDN

Blob

In all current engines.

Firefox4+Safari6+Chrome5+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile11+
Node.js18.0.0+
MDN

File/File

In all current engines.

Firefox28+Safari10.1+Chrome38+
Opera?Edge79+
Edge (Legacy)?IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
MDN

File/lastModified

In all current engines.

Firefox15+Safari10+Chrome13+
Opera15+Edge79+
Edge (Legacy)18IENone
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile14+
MDN

File/name

In all current engines.

Firefox3.6+Safari8+Chrome13+
Opera15+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile14+
MDN

File

In all current engines.

Firefox7+Safari4+Chrome13+
Opera11.5+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile11.5+
MDN

FileList/item

In all current engines.

Firefox3+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile12.1+
MDN

FileList/length

In all current engines.

Firefox3+Safari4+Chrome2+
Opera11.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile11.1+
MDN

FileList

In all current engines.

Firefox3+Safari4+Chrome2+
Opera11.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile11.1+
MDN

FileReader/FileReader

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile12.1+
MDN

FileReader/abort

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/abort_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/abort_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/error

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/error_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/error_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/load_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/load_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/loadend_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/loadend_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/loadstart_event

In all current engines.

Firefox79+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android79+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/loadstart_event

In all current engines.

Firefox79+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android79+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/progress_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/progress_event

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/readAsArrayBuffer

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera12+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile12+
MDN

FileReader/readAsBinaryString

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IENone
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/readAsDataURL

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/readAsText

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/readyState

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader/result

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReader

In all current engines.

Firefox3.6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android32+iOS Safari?Chrome for Android?Android WebView3+Samsung Internet?Opera Mobile11+
MDN

FileReaderSync/FileReaderSync

In all current engines.

Firefox8+Safari6+Chrome7+
Opera12.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

FileReaderSync/readAsArrayBuffer

In all current engines.

Firefox8+Safari6+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

FileReaderSync/readAsDataURL

In all current engines.

Firefox8+Safari6+Chrome7+
Opera12.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

FileReaderSync/readAsText

In all current engines.

Firefox8+Safari6+Chrome7+
Opera12.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

FileReaderSync

In all current engines.

Firefox8+Safari6+Chrome7+
Opera12.1+Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile12.1+
MDN

URL/createObjectURL_static

In all current engines.

Firefox19+Safari6+Chrome19+
Opera?Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
Node.js16.7.0+
MDN

URL/revokeObjectURL_static

In all current engines.

Firefox19+Safari6+Chrome19+
Opera?Edge79+
Edge (Legacy)12+IE10+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView?Samsung Internet?Opera Mobile?
Node.js16.7.0+