FileList
interface, which represents an array of individually selected files from the underlying system. The user interface for selection can be invoked via <in
put type="file">
, i.e. when the input element is in the File Upload
state [HTML].
ABlob
interface, which represents immutable raw binary data, and allows access to ranges of bytes within the B
lob
object as a separate Blob
.
AFile
interface, which includes readonly informational attributes about a file such as its name and the date of the last modification (on disk) of the file.
AFileReader
interface, which provides methods to read a F
ile
or a Blob
, and an event model to obtain the results of these reads.
AURL scheme for use with binary data such as files, so that they can be referenced within web applications.
Additionally, this specification defines objects to be used within threaded web applications for the synchronous reading of files.
§ 10 Requirements and Use Cases covers the motivation behind this specification.
This API is designed to be used in conjunction with other APIs and elements on the web platform, notably: XMLHttpRe
quest
(e.g. with an overloaded send()
method for File
orBlo
b
arguments), postM
essage()
, DataTrans
fer
(part of the drag and drop API defined in [HTML])
and Web Workers.
Additionally, it should be possible to programmatically obtain a list of files from the input
element
when it is in the File Upload
state [HTML].
These kinds of behaviors are defined in the appropriate affiliated specifications.
slice()
method
(二)3.3.2 The stream()
method
(三)3.3.3 The text
()
method
(四)3.3.4 The ar
rayBuf
fer()
method
(五)3.3.5 The by
tes()
method
(四)
4The File Interface
(一)
4.1 Constructor
(一)4.1.1 Constructor Parameters
(二)4.2 Attributes
(五)
5The FileList Interface
(一)5.1 Attributes
(二)5.2 Methods and Parameters
(六)
6Reading Data
(一)6.1 The File Reading Task Source
(二)
6.2 The F
ile
Rea
der
API
(一)6.2.1 Event Handler Content Attributes
(二)6.2.2 FileReader States
(三)
6.2.3 Reading a File or Blob
(一)6.2.3.1 The r
ead
AsD
ata
URL
()
method
(二)6.2.3.2 The r
ead
AsT
ext
()
method
(三)6.2.3.3 The r
ead
AsA
rra
yBu
ffe
r()
(四)6.2.3.4 The r
ead
AsB
ina
ryS
tri
ng()
method
(五)6.2.3.5 The a
bor
t()
method
(三)6.3 Packaging data
(四)
6.4 Events
(一)6.4.1 Event Summary
(二)6.4.2 Summary of Event Invariants
(五)
6.5 Reading on Threads
(一)
6.5.1 The
Fil
eRe
ade
rSy
nc
API
(一)6.5.1.1 Constructors
(二)6.5.1.2 The r
ead
AsT
ext
()
(三)6.5.1.3 The r
ead
AsD
ata
URL
()
method
(四)6.5.1.4 The r
ead
AsA
rra
yBu
ffe
r()
method
(五)6.5.1.5 The r
ead
AsB
ina
ryS
tri
ng()
method
(七)
7Errors and Exceptions
(一)7.1 Throwing an Exception or Returning an Error
(八)
8A URL for Blob and MediaSource reference
(一)8.1 Introduction
(二)8.2 Model
(三)
8.3 Dereferencing Model for blob URLs
(一)8.3.1 Origin of blob URLs
(二)8.3.2 Lifetime of blob URLs
(四)
8.4 Creating and Revoking a blob URL
(一)8.4.1 Examples of blob URL Creation and Revocation
(九)9Security and Privacy Considerations
(十)10Requirements and Use Cases
(11)Acknowledgements
(12)
Conformance
(一)Document conventions
(二)Conformant Algorithms
(13)
Index
(一)Terms defined by this specification
(二)Terms defined by reference
(14)
References
(一)Normative References
(二)Informative References
(15)IDL Index
(16)Issues Index
Fi
le
interface represents file data typically obtained from the underlying file system,
and the B
lob
interface
("Binary Large Object" - a name originally introduced to web APIs in Google Gears)
represents immutable raw data.
Fil
e
orB
lob
reads should happen asynchronously on the main thread,
with an optional synchronous API used within threaded web applications.
An asynchronous API for reading files prevents blocking and UI "freezing" on a user agent’s main thread.
This specification defines an asynchronous API based on an event model to read and access a F
ile
orBl
ob
’s data.
A F
ile
Rea
der
object provides asynchronous read methods to access that file’s data
through event handler content attributes and the firing of events.
The use of events and event handlers allows separate code blocks the ability
to monitor the progress of the read (which is particularly useful for remote drives or mounted drives,
where file access performance may vary from local drives)
and error conditions that may arise during reading of a file.
An example will be illustrative.
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 } else { // run other charset test } // xhr.send(fileString) } function errorHandler( evt) { if ( evt. target. error. name== "NotReadableError" ) { // The file could not be read } }
ab
ort
()
call.
The algorithms and steps in this specification use the following mathematical operations:
max(a,b) returns the maximum of a and b,
and is always performed on integers as they are defined in WebIDL [WebIDL];
in the case of max(6,4) the result is 6.
This operation is also defined in ECMAScript [ECMA-262].
min(a,b) returns the minimum of a and b,
and is always performed on integers as they are defined in WebIDL [WebIDL];
in the case of min(6,4) the result is 4.
This operation is also defined in ECMAScript [ECMA-262].
Mathematical comparisons such as < (less than), ≤ (less than or equal to), and > (greater than) are as in ECMAScript [ECMA-262].
The term Unix Epoch is used in this specification to refer to the time 00:00:00 UTC on January 1 1970
(or 1970-01-01T00:00:00Z ISO 8601);
this is the same time that is conceptually "0
" in ECMA-262 [ECMA-262].
The slice blob algorithm given a
Blo
b
blob, start, end, and contentType is used to refer to the following
steps and returns a new Bl
ob
containing the bytes ranging from the start parameter
up to but not including the end parameter. It must act as follows:
Let originalSizebeblob’s
siz
e
.
The start parameter, if non-null, is a value for the start point of a slice blob call, and must be treated as a byte-order position, with the zeroth position representing the
first byte. User agents must normalize start according to the following:
(あ)Ifstart is null, let relativeStart be 0.
(い)Ifstart is negative, let relativeStartbema
x((
ori
gin
alS
ize
+
sta
rt),
0)
.
(う)Otherwise, let relativeStartbemi
n(s
tar
t,
ori
gin
alS
ize)
.
The end parameter, if non-null. is a value for the end point of a slice blob call. User agents must normalize end according to the following:
(あ)Ifend is null, let relativeEndbeoriginalSize.
(い)Ifend is negative, let relativeEndbema
x((
ori
gin
alS
ize
+
end)
, 0)
.
(う)Otherwise, let relativeEndbem
in(
end,
or
igi
nal
Siz
e)
.
The contentType parameter, if non-null, is used to set the ASCII-encoded string in
lower case representing the media type of the
Blo
b
. User agents must normalize contentType according to the following:
(あ)IfcontentType is null, let relativeContentType be set to the empty
string.
(い)
Otherwise, let relativeContentType be set to contentType and run the
substeps below:
IfrelativeContentType contains any characters outside the range of U+0020 to
U+007E, then set relativeContentType to the empty string and return from these
substeps.
Convert every character in relativeContentTypetoASCII lowercase.
Let spanbemax
((r
ela
tiv
eEn
d -
re
lat
ive
Sta
rt),
0)
.
Return a new Bl
ob
object Swith the following characteristics:
(あ)Srefers to span consecutive bytes from blob’s
associated byte sequence, beginning with the byte at byte-order position relativeStart.
(い)S.s
ize
= span.
(う)S.t
ype
= relativeContentType.
Bl
ob
object refers to a byte sequence,
and has a si
ze
attribute which is the total number of bytes in the byte sequence,
and a
typ
e
attribute,
which is an ASCII-encoded string in lower case representing the media type of the byte sequence.
Each B
lob
must have an internal snapshot state,
which must be initially set to the state of the underlying storage,
if any such underlying storage exists.
Further normative definition of snapshot state can be found for
Fil
e
s.
[Exposed =(Window ,Worker ),Serializable ]interface {
Blob (
constructor optional sequence <BlobPart >blobParts ,optional BlobPropertyBag = {});
options readonly attribute unsigned long long size ;readonly attribute DOMString type ; // slice Blob into byte-ranged chunksBlob slice (optional [Clamp ]long long ,
start optional [Clamp ]long long ,
end optional DOMString ); // read from the Blob. [
contentType NewObject ]ReadableStream stream (); [NewObject ]Promise <USVString >text (); [NewObject ]Promise <ArrayBuffer >arrayBuffer (); [NewObject ]Promise <Uint8Array >bytes (); };enum {
EndingType ,
"transparent" };
"native" dictionary {
BlobPropertyBag DOMString type = "";EndingType endings = "transparent"; };typedef (BufferSource or Blob or USVString );
BlobPart
Blo
b
objects are serializable objects. Their serialization steps,
given value and serialized, are:
Set serialized.[[SnapshotState]] to value’s snapshot state.
Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
Their deserialization step, given serialized and value, are:
Set value’s snapshot statetoserialized.[[SnapshotState]].
Set value’s underlying byte sequence to serialized.[[ByteSequence]].
ABl
ob
blob has an associated get stream algorithm,
which runs these steps:
Let stream be a new R
ead
abl
eSt
rea
m
created in blob’s relevant Realm.
Set up stream with byte reading support.
Run the following steps in parallel:
While not all bytes of blob have been read:
Let bytes be the byte sequence that results from reading a chunk from blob, or
failure if a chunk cannot be read.
Queue a global task on the file reading task source given blob’s relevant global object to perform the following steps:
Ifbytes is failure, then error stream with a failure reason and
abort these steps.
Let chunk be a new Ui
nt8
Arr
ay
wrapping an
Arr
ayB
uff
er
containing bytes. If
creating the Ar
ray
Buf
fer
throws an exception, then error stream with that exception and abort these steps.
Enqueue chunkinstream.
We need to specify more concretely what reading from a Blob actually does,
what possible errors can happen, perhaps something about chunk sizes, etc.
Return stream.
Bl
ob()
constructor can be invoked with zero or more parameters.
When the
Blo
b()
constructor is invoked,
user agents must run the following steps:
If invoked with zero parameters,
return a new
Blo
b
object consisting of 0 bytes,
with s
ize
set to 0,
and with
typ
e
set to the empty string.
Let bytes be the result of processing blob parts given bl
obP
art
s
and
opt
ion
s
.
If the ty
pe
member of the o
pti
ons
argument is not the empty string,
run the following sub-steps:
Let tbe the
typ
e
dictionary member.
If tcontains any characters outside the range U+0020 to U+007E,
then set tto the empty string and return from these substeps.
Convert every character in ttoASCII lowercase.
Return a
Blo
b
object referring to bytes as its associated byte sequence,
with its
siz
e
set to the length of bytes,
and its ty
pe
set to the value of tfrom the substeps above.
Bl
ob()
constructor can be invoked with the parameters below:
Abl
obP
art
s
s
equ
enc
e
which takes any number of the following types of elements, and in any order:
Buf
fer
Sou
rce
elements.
Blo
b
elements.
USV
Str
ing
elements.
Anoptional Bl
obP
rop
ert
yBa
g
which takes these optional members:
typ
e
,
the ASCII-encoded string in lower case representing the media type of the Bl
ob
.
Normative conditions for this member are provided in the § 3.1 Constructors.
end
ing
s
,
an enum which can take the values
"tr
ans
par
ent
"
or"
nat
ive
"
.
By default this is set to "t
ran
spa
ren
t"
. If set to "
nat
ive
"
, line endings will be converted to native in any
USV
Str
ing
elements in bl
obP
art
s
.
Toprocess blob parts given a sequence of Bl
obP
art
's parts and Bl
obP
rop
ert
yBa
g
options,
run the following steps:
Let bytes be an empty sequence of bytes.
For each elementinparts:
Ifelement is a U
SVS
tri
ng
, run the following substeps:
Let sbeelement.
If the en
din
gs
member of optionsis
"na
tiv
e"
,
set sto the result of converting line endings to nativeofelement.
Append the result of UTF-8 encoding stobytes.
Note: The algorithm from WebIDL [WebIDL] replaces unmatched surrogates in an invalid utf-16 string
with U+FFFD replacement characters.
Scenarios exist when the Bl
ob
constructor may result in some data loss
due to lost or scrambled character sequences.
Ifelement is a B
uff
erS
our
ce
, get
a copy of the bytes held by the buffer source, and append those bytes to bytes.
Ifelement is a B
lob
,
append the bytes it represents to bytes.
Note: The ty
pe
of the Bl
ob
array element is ignored and will not affect
typ
e
of returned B
lob
object.
Return bytes.
Toconvert line endings to native in a string s,
run the following steps:
Let native line ending be be the code point U+000A LF.
If the underlying platform’s conventions are
to represent newlines as a carriage return and line feed sequence,
set native line ending to the code point U+000D CR
followed by the code point U+000A LF.
Set result to the empty string.
Let position be a position variable for s,
initially pointing at the start of s.
Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR
from sgiven position.
Append tokentoresult.
While position is not past the end of s:
If the code pointatposition within sequals U+000D CR:
Append native line endingtoresult.
Advance position by 1.
Ifposition is not past the end of sand the code pointatposition within sequals U+000A LF
advance position by 1.
Otherwise if the code pointatposition within sequals U+000A LF,
advance position by 1 and append native line endingtoresult.
Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR
from sgiven position.
Append tokentoresult.
Return result.
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]);
siz
e
, of type unsigned long long, readonly
Returns the size of the byte sequence in number of bytes.
On getting, conforming user agents must return the total number of bytes that can be read by a
Fil
eRe
ade
r
orF
ile
Rea
der
Syn
c
object,
or 0 if the Bl
ob
has no bytes to be read.
typ
e
, of type DOMString, readonly
The ASCII-encoded string in lower case representing the media type of the B
lob
.
On getting, user agents must return the type of a
Blo
b
as an ASCII-encoded string in lower case,
such that when it is converted to a byte sequence,
it is a parsable MIME type,
or the empty string – 0 bytes – if the type cannot be determined.
The ty
pe
attribute can be set by the web application itself through constructor invocation
and through the s
lic
e()
call;
in these cases, further normative conditions for this attribute are in § 3.1 Constructors, § 4.1 Constructor,
and § 3.3.1 The slice() method respectively.
User agents can also determine the
typ
e
of a Bl
ob
,
especially if the byte sequence is from an on-disk file;
in this case, further normative conditions are in the file type guidelines.
Note: The type tof a
Blo
b
is considered a parsable MIME type,
if performing the parse a MIME type algorithm to a byte sequence converted from
the ASCII-encoded string representing the Blob object’s type does not return failure.
Note: Use of the t
ype
attribute informs the package data algorithm
and determines the C
ont
ent
-Ty
pe
header when fetching blob URLs.
sl
ice
()
method
sl
ice
()
method
returns a new B
lob
object with bytes ranging from the optional start parameter
up to but not including the optional end parameter, and with a
typ
e
attribute
that is the value of the optional contentType parameter. It must act as follows:
Let sliceStart, sliceEnd, and sliceContentType be null.
Ifstart is given, set sliceStarttostart.
Ifend is given, set sliceEndtoend.
IfcontentType is given, set sliceContentTypetocontentType.
Return the result of slice blob given this, sliceStart, sliceEnd, and sliceContentType.
The examples below illustrate the different types of s
lic
e()
calls possible. Since the F
ile
interface inherits from the B
lob
interface, examples are based on the use of the Fi
le
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" ); }
st
rea
m()
method
st
rea
m()
method, when invoked, must return
the result of calling get streamonthis.
te
xt()
method
te
xt()
method, when invoked, must run these steps:
Let stream be the result of calling get streamonthis.
Let reader be the result of getting a reader from stream.
If that threw an exception, return a new promise rejected with that exception.
Let promise be the result of reading all bytes from stream with reader.
Return the result of transforming promise by a fulfillment handler that returns the result of
running UTF-8 decode on its first argument.
Note: This is different from the behavior of
rea
dAs
Tex
t()
to align better
with the behavior of Fe
tch
’s
tex
t()
. Specifically this method will always
use UTF-8 as encoding, while
Fil
eRe
ade
r
can use a different encoding depending on
the blob’s type and passed in encoding name.
ar
ray
Buf
fer
()
method
ar
ray
Buf
fer
()
method, when invoked, must run these steps:
Let stream be the result of calling get streamonthis.
Let reader be the result of getting a reader from stream.
If that threw an exception, return a new promise rejected with that exception.
Let promise be the result of reading all bytes from stream with reader.
Return the result of transforming promise by a fulfillment handler that returns
a new A
rra
yBu
ffe
r
whose contents are its first argument.
by
tes
()
method
by
tes
()
method, when invoked, must run these steps:
Let stream be the result of calling get streamonthis.
Let reader be the result of getting a reader from stream.
If that threw an exception, return a new promise rejected with that exception.
Let promise be the result of reading all bytes from stream with reader.
Return the result of transforming promise by a fulfillment handler that returns
a new U
int
8Ar
ray
wrapping an Ar
ray
Buf
fer
containing its first argument.
Fi
le
object is a
Blo
b
object with a na
me
attribute, which is a string;
it can be created within the web application via a constructor,
or is a reference to a byte sequence from a file from the underlying (OS) file system.
If a F
ile
object is a reference to a byte sequence originating from a file on disk,
then its snapshot state should be set to the state of the file on disk at the time the F
ile
object is created.
Note: This is a non-trivial requirement to implement for user agents,
and is thus not a must but a should [RFC2119].
User agents should endeavor to have a F
ile
object’s snapshot state set to the state of the underlying storage on disk at the time the reference is taken.
If the file is modified on disk following the time a reference has been taken,
the Fi
le
's snapshot state will differ from the state of the underlying storage.
User agents may use modification time stamps and other mechanisms to maintain snapshot state,
but this is left as an implementation detail.
When a Fi
le
object refers to a file on disk,
user agents must return the
typ
e
of that file,
and must follow the file type guidelines below:
User agents must return the ty
pe
as an ASCII-encoded string in lower case,
such that when it is converted to a corresponding byte sequence,
it is a parsable MIME type,
or the empty string – 0 bytes – if the type cannot be determined.
When the file is of type te
xt/
pla
in
user agents must NOT append a charset parameter to the dictionary of parameters portion of the media type [MIMESNIFF].
User agents must not attempt heuristic determination of encoding,
including statistical methods.
[Exposed =(Window ,Worker ),Serializable ]interface :
File Blob {(
constructor sequence <BlobPart >fileBits ,USVString fileName ,optional FilePropertyBag = {});
options readonly attribute DOMString name ;readonly attribute long long lastModified ; };dictionary :
FilePropertyBag BlobPropertyBag {long long lastModified ; };
Fil
e
objects are serializable objects. Their serialization steps,
given value and serialized, are:
Set serialized.[[SnapshotState]] to value’s snapshot state.
Set serialized.[[ByteSequence]] to value’s underlying byte sequence.
Set serialized.[[Name]] to the value of value’s n
ame
attribute.
Set serialized.[[LastModified]] to the value of value’s la
stM
odi
fie
d
attribute.
Their deserialization steps, given value and serialized, are:
Set value’s snapshot statetoserialized.[[SnapshotState]].
Set value’s underlying byte sequence to serialized.[[ByteSequence]].
Initialize the value of value’s n
ame
attribute to serialized.[[Name]].
Initialize the value of value’s l
ast
Mod
ifi
ed
attribute to serialized.[[LastModified]].
Fi
le
constructor is invoked with two or three parameters,
depending on whether the optional dictionary parameter is used.
When the
Fil
e()
constructor is invoked,
user agents must run the following steps:
Let bytes be the result of processing blob parts given fi
leB
its
and o
pti
ons
.
Let nbe the
fil
eNa
me
argument 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 to byte sequences.
Process F
ile
Pro
per
tyB
ag
dictionary argument by running the following substeps:
If the ty
pe
member is provided and is not the empty string,
let tbe set to the
typ
e
dictionary member.
If tcontains any characters outside the range U+0020 to U+007E,
then set tto the empty string and return from these substeps.
Convert every character in ttoASCII lowercase.
If the la
stM
odi
fie
d
member is provided,
let dbe set to the la
stM
odi
fie
d
dictionary member.
If it is not provided,
set dto the current date and time
represented as the number of milliseconds since the Unix Epoch (which is the equivalent of Da
te.
now
()
[ECMA-262]).
Note: Since ECMA-262
Dat
e
objects convert to lon
g l
ong
values
representing the number of milliseconds since the Unix Epoch,
the
las
tMo
dif
ied
member could be a Da
te
object [ECMA-262].
Return a new Fi
le
object Fsuch that:
Frefers to the bytes byte sequence.
F.s
ize
is set to the number of total bytes in bytes.
F.n
ame
is set to n.
F.t
ype
is set to t.
F.l
ast
Mod
ifi
ed
is set to d.
Fi
le()
constructor can be invoked with the parameters below:
Afi
leB
its
se
que
nce
which takes any number of the following elements, and in any order:
Buf
fer
Sou
rce
elements.
Blo
b
elements, which includes
Fil
e
elements.
USV
Str
ing
elements.
Afi
leN
ame
parameter
AUS
VSt
rin
g
parameter representing the name of the file;
normative conditions for this constructor parameter can be found in § 4.1 Constructor.
An optional
Fil
ePr
ope
rty
Bag
dictionary
which in addition to the membersof
Blo
bPr
ope
rty
Bag
takes one member:
An optional las
tMo
dif
ied
member,
which must be a lon
g l
ong
;
normative conditions for this member are provided in § 4.1 Constructor.
nam
e
, of type DOMString, readonly
The name of the file.
On getting, this must return the name of the file as a string.
There are numerous file name variations and conventions used by different underlying OS file systems;
this is merely the name of the file, without path information.
On getting, if user agents cannot make this information available,
they must return the empty string.
If a F
ile
object is created using a constructor,
further normative conditions for this attribute are found in § 4.1 Constructor.
las
tMo
dif
ied
, of type long long, readonly
The last modified date of the file.
On getting, if user agents can make this information available,
this must return a l
ong
lo
ng
set to the time the file was last modified
as the number of milliseconds since the Unix Epoch.
If the last modification date and time are not known,
the attribute must return the current date and time
as a lo
ng
lon
g
representing the number of milliseconds since the Unix Epoch;
this is equivalent to D
ate.
now
()
[ECMA-262].
If a Fi
le
object is created using a constructor,
further normative conditions for this attribute are found in § 4.1 Constructor.
The Fi
le
interface is available on objects that expose an attribute of type Fi
leL
ist
;
these objects are defined in HTML [HTML].
The Fi
le
interface, which inherits from
Blo
b
, is immutable,
and thus represents file data that can be read into memory at the time a read operation is initiated.
User agents must process reads on files that no longer exist at the time of read as errors,
throwing a N
otF
oun
dEr
ror
exception
if using a
Fil
eRe
ade
rSy
nc
on a Web Worker [Workers] or firing an e
rro
r
event
with the er
ror
attribute returning a N
otF
oun
dEr
ror
.
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.
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}) ...
Fi
leL
ist
interface should be considered "at risk"
since the general trend on the Web Platform is to replace such interfaces
with the
Arr
ay
platform object in ECMAScript [ECMA-262].
In particular, this means syntax of the sort fi
lel
ist.
ite
m( 0 )
is at risk;
most other programmatic use of Fi
leL
ist
is unlikely to be affected by the eventual migration to an
Arr
ay
type.
This interface is a list of Fi
le
objects.
[Exposed =(Window ,Worker ),Serializable ]interface {
FileList getter File ?item (unsigned long index );readonly attribute unsigned long length ; };
Fil
eLi
st
objects are serializable objects. Their serialization steps,
given value and serialized, are:
Set serialized.[[Files]] to an empty list.
For each fileinvalue, append the sub-serializationoffiletoserialized.[[Files]].
Their deserialization step, given serialized and value, are:
For each fileofserialized.[[Files]], add the sub-deserializationoffiletovalue.
Sample usage typically involves DOM access to the <
inp
ut
typ
e="
fil
e">
element within a form,
and then accessing selected files.
// uploadData is a form element // fileChooser is input element of type 'file' var file= document. forms[ 'uploadData' ][ 'fileChooser' ]. files[ 0 ]; // alternative syntax can be // var file = document.forms['uploadData']['fileChooser'].files.item(0); if ( file) { // Perform file ops }
len
gth
, of type unsigned long, readonly
must return the number of files in the
Fil
eLi
st
object.
If there are no files, this attribute must return 0.
ite
m(i
nde
x)
must return the indexthFi
le
object in the F
ile
Lis
t
.
If there is no indexth
Fil
e
object in the Fi
leL
ist
,
then this method must return nul
l
.
ind
ex
must be treated by user agents
as value for the position of a F
ile
object in the
Fil
eLi
st
,
with 0 representing the first file. Supported property indices are the numbers in the range zero
to one less than the number of
Fil
e
objects represented by the F
ile
Lis
t
object.
If there are no such Fi
le
objects,
then there are no supported property indices.
Note: The HT
MLI
npu
tEl
eme
nt
interface has a readonly attribute of type Fi
leL
ist
,
which is what is being accessed in the above example.
Other interfaces with a readonly attribute of type F
ile
Lis
t
include the D
ata
Tra
nsf
er
interface.
Bl
ob
and Fi
le
objects.
It is to be used for features that trigger in response to asynchronously reading binary data.
F
ile
Rea
der
API
[AExposed =(Window ,Worker )]interface :
FileReader EventTarget {constructor (); // async read methodsundefined readAsArrayBuffer (Blob );
blob undefined readAsBinaryString (Blob );
blob undefined readAsText (Blob ,
blob optional DOMString );
encoding undefined readAsDataURL (Blob );
blob undefined abort (); // statesconst unsigned short = 0;
EMPTY const unsigned short = 1;
LOADING const unsigned short = 2;
DONE readonly attribute unsigned short readyState ; // File or Blob datareadonly attribute (DOMString or ArrayBuffer )?result ;readonly attribute DOMException ?error ; // event handler content attributesattribute EventHandler onloadstart ;attribute EventHandler onprogress ;attribute EventHandler onload ;attribute EventHandler onabort ;attribute EventHandler onerror ;attribute EventHandler onloadend ; };
Fi
leR
ead
er
has an associated state,
that is "
emp
ty"
, "l
oad
ing
"
, or "do
ne"
. It is initially "
emp
ty"
.
AFi
leR
ead
er
has an associated result (n
ull
, a
DOM
Str
ing
or an Ar
ray
Buf
fer
). It is initially nul
l
.
AFi
leR
ead
er
has an associated error (nu
ll
or a D
OME
xce
pti
on
). It is initially n
ull
.
The Fi
leR
ead
er()
constructor,
when invoked, must return a new Fi
leR
ead
er
object.
The re
ady
Sta
te
attribute’s getter,
when invoked, switches on this's state and runs the associated step:
"em
pty
"
Return EM
PTY
"lo
adi
ng"
Return LO
ADI
NG
"do
ne"
Return DO
NE
The re
sul
t
attribute’s getter,
when invoked, must return this's result.
The er
ror
attribute’s getter,
when invoked, must return this's error.
AFi
leR
ead
er
frhas an associated read operation algorithm,
which given blob, a type and an optional encodingName,
runs the following steps:
Iffr’s stateis"
loa
din
g"
,
throw an In
val
idS
tat
eEr
ror
DO
MEx
cep
tio
n
.
Set fr’s stateto"
loa
din
g"
.
Set fr’s resulttonul
l
.
Set fr’s errorton
ull
.
Let stream be the result of calling get streamonblob.
Let reader be the result of getting a reader from stream.
Let bytes be an empty byte sequence.
Let chunkPromise be the result of reading a chunk from stream with reader.
Let isFirstChunk be true.
In parallel, while true:
Wait for chunkPromise to be fulfilled or rejected.
IfchunkPromise is fulfilled, and isFirstChunk is true, queue a tasktofire a progress event called
loa
dst
art
atfr.
We might change lo
ads
tar
t
to be dispatched synchronously,
to align with XMLHttpRequest behavior. [Issue #119]
Set isFirstChunk to false.
IfchunkPromise is fulfilled with an object whose don
e
property is false and whose val
ue
property is a U
int
8Ar
ray
object, run these steps:
Let bsbe the byte sequence represented by the Uin
t8A
rra
y
object.
Append bstobytes.
If roughly 50ms have passed since these steps were last invoked, queue a tasktofire a progress event called pr
ogr
ess
atfr.
Set chunkPromise to the result of reading a chunk from stream with reader.
Otherwise, if chunkPromise is fulfilled with an object whose don
e
property is true, queue a task to run the following steps and abort this algorithm:
Set fr’s stateto"
don
e"
.
Let result be the result of package data given bytes, type, blob’s ty
pe
, and encodingName.
Ifpackage data threw an exception error:
Set fr’s errortoerror.
Fire a progress event called e
rro
r
atfr.
Else:
Set fr’s resulttoresult.
Fire a progress event called l
oad
at the fr.
Iffr’s state is not "lo
adi
ng"
, fire a progress event called
loa
den
d
at the fr.
Note: Event handler for the lo
ad
or
err
or
events could have started another load,
if that happens the
loa
den
d
event for this load is not fired.
Otherwise, if chunkPromise is rejected with an error error, queue a task to run the following steps and abort this algorithm:
Set fr’s stateto"
don
e"
.
Set fr’s errortoerror.
Fire a progress event called e
rro
r
atfr.
Iffr’s state is not "lo
adi
ng"
, fire a progress event called
loa
den
d
atfr.
Note: Event handler for the er
ror
event could have started another load,
if that happens the
loa
den
d
event for this load is not fired.
Use the file reading task source for all these tasks.
Fil
eRe
ade
r
as DOM attributes:
event handler content attribute | event handler event type |
---|---|
onloadstart
| loadstart
|
onprogress
| progress
|
onabort
| abort
|
onerror
| error
|
onload
| load
|
onloadend
| loadend
|
Fi
leR
ead
er
object can be in one of 3 states.
The re
ady
Sta
te
attribute tells you in which state the object is:
EMP
TY
(numeric value 0)
The Fi
leR
ead
er
object has been constructed,
and there are no pending reads.
None of the read methods have been called.
This is the default state of a newly minted
Fil
eRe
ade
r
object,
until one of the read methods have been called on it.
LOA
DIN
G
(numeric value 1)
AFi
le
or
Blo
b
is being read.
One of the read methods is being processed,
and no error has occurred during the read.
DON
E
(numeric value 2)
The entire F
ile
orBl
ob
has been read into memory,
OR a file read error occurred,
OR the read was aborted using ab
ort
()
.
The F
ile
Rea
der
is no longer reading a
Fil
e
orB
lob
.
If re
ady
Sta
te
is set to DO
NE
it means at least one of the read methods have been called on this Fi
leR
ead
er
.
Fi
leR
ead
er
interface makes available several asynchronous read methods—
rea
dAs
Arr
ayB
uff
er()
, r
ead
AsB
ina
ryS
tri
ng()
, r
ead
AsT
ext
()
and re
adA
sDa
taU
RL()
,
which read files into memory.
Note: If multiple concurrent read methods are called on the same F
ile
Rea
der
object,
user agents throw an I
nva
lid
Sta
teE
rro
r
on any of the read methods that occur
when r
ead
ySt
ate
=
LOA
DIN
G
.
(Fi
leR
ead
erS
ync
makes available several synchronous read methods.
Collectively, the sync and async read methods of
Fil
eRe
ade
r
and
Fil
eRe
ade
rSy
nc
are referred to as just read methods.)
r
ead
AsD
ata
URL
()
method
re
adA
sDa
taU
RL(
blo
b)
method,
when invoked, must initiate a read operation for blob with DataURL.
r
ead
AsT
ext
()
method
re
adA
sTe
xt(
blo
b,
enc
odi
ng)
method,
when invoked, must initiate a read operation for blob with Text and encoding.
r
ead
AsA
rra
yBu
ffe
r()
re
adA
sAr
ray
Buf
fer
(bl
ob)
method,
when invoked, must initiate a read operation for blob with ArrayBuffer.
r
ead
AsB
ina
ryS
tri
ng()
method
re
adA
sBi
nar
ySt
rin
g(b
lob)
method,
when invoked, must initiate a read operation for blob with BinaryString.
Note: The use of r
ead
AsA
rra
yBu
ffe
r()
is preferred over re
adA
sBi
nar
ySt
rin
g()
, which is provided for backwards
compatibility.
a
bor
t()
method
abo
rt()
method is called,
the user agent must run the steps below:
Ifthis's stateis"
emp
ty"
or if this's stateis"
don
e"
set this's resulttonul
l
and terminate this algorithm.
Ifthis's stateis"
loa
din
g"
set this's stateto"
don
e"
and set this's resulttonu
ll
.
If there are any tasks from this on the file reading task source in an affiliated task queue,
then remove those tasks from that task queue.
Terminate the algorithm for the read method being processed.
Fire a progress event called a
bor
t
atthis.
Ifthis's state is not "lo
adi
ng"
, fire a progress event called
loa
den
d
atthis.
Bl
ob
has an associated package data algorithm,
given bytes, a type, a optional mimeType, and a optional encodingName,
which switches on type and runs the associated steps:
DataURL
Return bytes as a DataURL [RFC2397] subject to the considerations below:
Use mimeType as part of the Data URL if it is available
in keeping with the Data URL specification [RFC2397].
IfmimeType is not available return a Data URL without a media-type. [RFC2397].
Better specify how the DataURL is generated. [Issue #104]
Text
Let encoding be failure.
If the encodingName is present, set encoding to the result of getting an encoding from encodingName.
Ifencoding is failure, and mimeType is present:
Let type be the result of parse a MIME type given mimeType.
Iftype is not failure,
set encoding to the result of getting an encoding from type’s parameters["
cha
rse
t"
].
Ifbl
ob
has a
typ
e
attribute of tex
t/p
lai
n;c
har
set
=ut
f-8
then getting an encoding is run using "ut
f-8
"
as the label.
Note that user agents must parse and extract the portion of the Charset Parameter
that constitutes a label of an encoding.
Ifencoding is failure, then set encodingtoUTF-8.
Decode bytes using fallback encoding encoding, and return the result.
ArrayBuffer
Return a new Ar
ray
Buf
fer
whose contents are bytes.
BinaryString
Return bytes as a binary string,
in which every byte is represented by a code unit of equal value [0..255].
Fi
leR
ead
er
object must be the event target for all events in this specification.
When this specification says to fire a progress event called e (for some Pr
ogr
ess
Eve
nt
e
at a given
Fil
eRe
ade
r
r
ead
er
),
the following are normative:
The progress event e
does not bubble. e.
bub
ble
s
must be false [DOM]
The progress event e
is NOT cancelable. e.c
anc
ela
ble
must be false [DOM]
F
ile
Rea
der
objects.
Event name | Interface | Fired when… |
---|---|---|
loadstart
| ProgressEvent
| When the read starts. |
progress
| ProgressEvent
| While reading (and decoding) blob
|
abort
| ProgressEvent
| When the read has been aborted.
For instance, by invoking the abort() method.
|
error
| ProgressEvent
| When the read has failed (see file read errors). |
load
| ProgressEvent
| When the read has successfully completed. |
loadend
| ProgressEvent
| When the request has completed (either in success or failure). |
lo
ads
tar
t
has been fired,
a corresponding
loa
den
d
fires at completion of the read,
UNLESS any of the following are true:
the read method has been cancelled using a
bor
t()
and a new read method has been invoked
the event handler function for a
loa
d
event initiates a new read
the event handler function for a
err
or
event initiates a new read.
Note: The events l
oad
sta
rt
and lo
ade
nd
are not coupled in a one-to-one manner.
This example showcases "read-chaining":
initiating another read from within an event handler while the "first" read continues processing.
One// 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
pr
ogr
ess
event will fire when bl
ob
has been completely read into memory.
Nopr
ogr
ess
event fires before l
oad
sta
rt
.
Nopr
ogr
ess
event fires after any one of
abo
rt
, lo
ad
, and e
rro
r
have fired.
At most one of
abo
rt
, lo
ad
, and e
rro
r
fire for a given read.
Noab
ort
, lo
ad
, or er
ror
event fires after lo
ade
nd
.
Fil
e
orB
lob
read APIs,
since such reads on threads do not block the main thread.
This section defines a synchronous API, which can be used within Workers [[Web Workers]].
Workers can avail of both the asynchronous API (the Fi
leR
ead
er
object) and the synchronous API (the
Fil
eRe
ade
rSy
nc
object).
Fi
leR
ead
erS
ync
API
Fil
e
orB
lob
objects into memory.
[Exposed =(DedicatedWorker ,SharedWorker )]interface {
FileReaderSync (); // Synchronously return strings
constructor ArrayBuffer readAsArrayBuffer (Blob );
blob DOMString readAsBinaryString (Blob );
blob DOMString readAsText (Blob ,
blob optional DOMString );
encoding DOMString readAsDataURL (Blob ); };
blob
Fil
eRe
ade
rSy
nc()
constructor is invoked,
the user agent must return a new
Fil
eRe
ade
rSy
nc
object.
r
ead
AsT
ext
()
re
adA
sTe
xt(
blo
b,
enc
odi
ng)
method,
when invoked, must run these steps:
Let stream be the result of calling get streamonblob.
Let reader be the result of getting a reader from stream.
Let promise be the result of reading all bytes from stream with reader.
Wait for promise to be fulfilled or rejected.
Ifpromise fulfilled with a byte sequence bytes:
Return the result of package data given bytes, Text, blob’s t
ype
, and encoding.
Throw promise’s rejection reason.
r
ead
AsD
ata
URL
()
method
re
adA
sDa
taU
RL(
blo
b)
method,
when invoked, must run these steps:
Let stream be the result of calling get streamonblob.
Let reader be the result of getting a reader from stream.
Let promise be the result of reading all bytes from stream with reader.
Wait for promise to be fulfilled or rejected.
Ifpromise fulfilled with a byte sequence bytes:
Return the result of package data given bytes, DataURL, and blob’s
typ
e
.
Throw promise’s rejection reason.
r
ead
AsA
rra
yBu
ffe
r()
method
re
adA
sAr
ray
Buf
fer
(bl
ob)
method,
when invoked, must run these steps:
Let stream be the result of calling get streamonblob.
Let reader be the result of getting a reader from stream.
Let promise be the result of reading all bytes from stream with reader.
Wait for promise to be fulfilled or rejected.
Ifpromise fulfilled with a byte sequence bytes:
Return the result of package data given bytes, ArrayBuffer, and blob’s
typ
e
.
Throw promise’s rejection reason.
r
ead
AsB
ina
ryS
tri
ng()
method
re
adA
sBi
nar
ySt
rin
g(b
lob)
method,
when invoked, must run these steps:
Let stream be the result of calling get streamonblob.
Let reader be the result of getting a reader from stream.
Let promise be the result of reading all bytes from stream with reader.
Wait for promise to be fulfilled or rejected.
Ifpromise fulfilled with a byte sequence bytes:
Return the result of package data given bytes, BinaryString, and blob’s t
ype
.
Throw promise’s rejection reason.
Note: The use of r
ead
AsA
rra
yBu
ffe
r()
is preferred over re
adA
sBi
nar
ySt
rin
g()
, which is provided for
backwards compatibility.
Fi
le
or
Blo
b
being accessed may not exist
at the time one of the asynchronous read methodsorsynchronous read methods are called.
This may be due to it having been moved or deleted after a reference to it was acquired
(e.g. concurrent modification with another application).
See N
otF
oun
dEr
ror
.
AFi
le
or
Blo
b
may be unreadable.
This may be due to permission problems that occur after a reference to a
Fil
e
orB
lob
has been acquired
(e.g. concurrent lock with another application).
Additionally, the snapshot state may have changed.
See No
tRe
ada
ble
Err
or
.
User agents MAY determine that some files are unsafe for use within Web applications.
A file may change on disk since the original file selection,
thus resulting in an invalid read.
Additionally, some file and directory structures may be considered restricted by the underlying filesystem;
attempts to read from them may be considered a security violation.
See § 9 Security and Privacy Considerations and
Sec
uri
tyE
rro
r
.
Fil
e
or a Bl
ob
.
The read operation can terminate due to error conditions when reading a
Fil
e
or a Bl
ob
;
the particular error condition that causes the get stream algorithm to fail
is called a failure reason. A failure reason is one of NotFound, UnsafeFile, TooManyReads, SnapshotState, or FileLock.
Synchronous read methods throw exceptions of the type in the table below
if there has been an error owing to a particular failure reason.
Asynchronous read methods use the er
ror
attribute of the
Fil
eRe
ade
r
object,
which must return a D
OME
xce
pti
on
object of the most appropriate type from the table below
if there has been an error owing to a particular failure reason,
or otherwise return null.
Type | Description and Failure Reason |
---|---|
NotFoundError
|
If the File orBlob resource could not be found at the time the read was processed,
this is the NotFound failure reason.
For asynchronous read methods the |
SecurityError
|
If:
For asynchronous read methods the This is a security error to be used in situations not covered by any other failure reason. |
NotReadableError
|
If:
For asynchronous read methods the |
This section defines a scheme for a URL used to refer to Blob
and MediaSource
objects.
This section is informative.
Blob (or object) URLs are URLs like blob:http://example.com/550e8400-e29b-41d4-a716-446655440000
.
This enables integration of Blob
s and MediaSource
s with other
APIs that are only designed to be used with URLs, such as the img
element. Blob URLs can also be used to navigate to as well as to trigger downloads
of locally generated data.
For this purpose two static methods are exposed on the URL
interface, createObjectURL(obj)
and revokeObjectURL(url)
.
The first method creates a mapping from a URL to a Blob
,
and the second method revokes said mapping.
As long as the mapping exist the Blob
can’t be garbage collected,
so some care must be taken to revoke the URL as soon as the reference is no longer needed.
All URLs are revoked when the global that created the URL itself goes away.
Each user agent must maintain a blob URL store. A blob URL store is a map where keys are valid URL strings and values are blob URL Entries.
Ablob URL entry consists of
an object (of type Blob
orMediaSource
),
and an environment (anenvironment settings object).
Keys in the blob URL store (also known as blob URLs)
are valid URL strings that when parsed result in a URL with a scheme equal to "blob
",
an empty host, and a path consisting of one element itself also a valid URL string.
Let result be the empty string.
Append the string "blob:
" to result.
Let settings be the current settings object
Let originbesettings’s origin.
Let serialized be the ASCII serializationoforigin.
Ifserialized is "null
", set it to an implementation-defined value.
Append serializedtoresult.
Append U+0024 SOLIDUS (/
) to result.
Generate a UUID [RFC4122] as a string and append it to result.
Return result.
blob:https://example.org/40a5fb5a-d56d-4a33-b4e2-0acf6a8e5f64
. Let store be the user agent’s blob URL store.
Let url be the result of generating a new blob URL.
Let entry be a new blob URL entry consisting of object and the current settings object.
Set store[url] to entry.
Return url.
Let store be the user agent’s blob URL store;
Let url string be the result of serializing url.
Remove store[url string].
Let store be the user agent’s blob URL store.
Let url string be the result of serializing url with the exclude fragment flag set.
Ifstore[url string] exists, return store[url string]; otherwise return failure.
Futher requirements for the parsing and fetching model for blob URLs are defined in the [URL] and [Fetch] specifications.
This section is informative.
The origin of a blob URL is always the same as that of the environment that created the URL, as long as the URL hasn’t been revoked yet. This is achieved by the [URL] spec looking up the URL in the blob URL store when parsing a URL, and using that entry to return the correct origin.
If the URL was revoked the serialization of the origin will still remain the same as the serialization of the origin of the environment that created the blob URL, but for opaque origins the origin itself might be distinct. This difference isn’t observable though, since a revoked blob URL can’t be resolved/fetched anymore anyway.
This specification extends the unloading document cleanup steps with the following steps:
Let environment be the Document
's relevant settings object.
Let store be the user agent’s blob URL store;
Remove from store any entries for which the value's environment is equal to environment.
This needs a similar hook when a worker is unloaded.
Blob URLs are created and revoked using static methods exposed on the URL
object.
Revocation of a blob URL decouples the blob URL from the resource it refers to,
and if it is dereferenced after it is revoked,
user agents must act as if a network error has occurred.
This section describes a supplemental interface to the URL specification [URL] and presents methods for blob URL creation and revocation.
[Exposed =(Window ,DedicatedWorker ,SharedWorker )]partial interface URL {static DOMString createObjectURL ((Blob or MediaSource ));
obj static undefined revokeObjectURL (DOMString ); };
url
createObjectURL(obj)
static method must
return the result of adding an entry to the blob URL store for obj. revokeObjectURL(url)
static method must run these steps:
Let url record be the result of parsing url.
Ifurl record’s scheme is not "blob
", return.
Let origin be the originofurl record.
Let settings be the current settings object.
Iforigin is not same origin with settings’s origin, return.
Remove an entry from the Blob URL Store for url.
Note: This means that rather than throwing some kind of error, attempting to revoke a URL that isn’t registered will silently fail. User agents might display a message on the error console if this happens.
Note: Attempts to dereference url after it has been revoked will result in a network error. Requests that were started before the url was revoked should still succeed.
window1
and window2
are separate,
but in the same origin; window2
could be an iframe
inside window1
.
myurl= window1. URL. createObjectURL( myblob); window2. URL. revokeObjectURL( myurl);
Since a user agent has one global blob URL store,
it is possible to revoke an object URL from a different window than from which it was created.
The URL.
call
ensures that subsequent dereferencing of revokeObjectURL()
myurl
results in a the user agent acting as if a network error has occurred.
Blob URLs are strings that are used to fetch Blob
objects,
and can persist for as long as the document
from which they were minted
using URL.
—createObjectURL()
This section gives sample usage of creation and revocation of blob URLs with explanations.
img
elements [HTML] refer to the same blob URL:
url= URL. createObjectURL( blob); img1. src= url; img2. src= url;
URL.revokeObjectURL()
is explicitly called.
var blobURLref= URL. createObjectURL( file); img1= new Image(); img2= new Image(); // Both assignments below work as expected img1. src= blobURLref; img2. src= blobURLref; // ... Following body load // Check if both images have loaded if ( img1. complete&& img2. complete) { // Ensure that subsequent refs throw an exception URL. revokeObjectURL( blobURLref); } else { msg( "Images cannot be previewed!" ); // revoke the string-based reference URL. revokeObjectURL( blobURLref); }
The example above allows multiple references to a single blob URL,
and the web developer then revokes the blob URL string after both image objects have been loaded.
While not restricting number of uses of the blob URL offers more flexibility,
it increases the likelihood of leaks;
developers should pair it with a corresponding call to URL.
.revokeObjectURL()
This section is informative.
This specification allows web content to read files from the underlying file system,
as well as provides a means for files to be accessed by unique identifiers,
and as such is subject to some security considerations.
This specification also assumes that the primary user interaction is with the <input type="file"/>
element of HTML forms [HTML],
and that all files that are being read by FileReader
objects have first been selected by the user.
Important security considerations include preventing malicious file selection attacks (selection looping),
preventing access to system-sensitive files,
and guarding against modifications of files on disk after a selection has taken place.
During file selection, a user may be bombarded with the file picker associated with <input type="file"/>
(in a "must choose" loop that forces selection before the file picker is dismissed)
and a user agent may prevent file access to any selections by making the FileList
object returned be of size 0.
(e.g. files in /usr/bin, password files, and other native operating system executables)
typically should not be exposed to web content,
and should not be accessed via blob URLs.
User agents may throwaSecurityError
exception for synchronous read methods,
or return a SecurityError
exception for asynchronous reads.
This section is provisional; more security data may supplement this in subsequent drafts.
This section covers what the requirements are for this API, as well as illustrates some use cases. This version of the API does not satisfy all use cases; subsequent versions may elect to address these.
Once a user has given permission, user agents should provide the ability to read and parse data directly from a local file programmatically.
Data should be able to be stored locally so that it is available for later use, which is useful for offline data access for web applications.
text/calendar
file is parsed in the browser,
allowing the user to merge the files to one calendar view.
The user wants to then save the file back to his local calendar file (using "Save As"?).
The user can also send the integrated calendar file back to the server calendar store asynchronously. User agents should provide the ability to save a local file programmatically given an amount of data and a file name.
Note: While this specification doesn’t provide an explicit API call to trigger downloads,
the HTML5 specification has addressed this.
The download
attribute of the a
element initiates a download,
saving a File
with the name specified.
The combination of this API and the download
attribute on a
elements
allows for the creation of files within web applications,
and the ability to save them locally.
User agents should provide a streamlined programmatic ability to send data from a file to a remote server that works more efficiently than form-based uploads today.
User agents should provide an API exposed to script that exposes the features above. The user is notified by UI anytime interaction with the file system takes place, giving the user full ability to cancel or abort the transaction. The user is notified of any file selections, and can cancel these. No invocations to these APIs occur silently without user intervention.
This specification was originally developed by the SVG Working Group. Many thanks to Mark Baker and Anne van Kesteren for their feedback.
Thanks to Robin Berjon, Jonas Sicking and Vsevolod Shmyroff for editing the original specification.
Special thanks to Olli Pettay, Nikunj Mehta, Garrett Smith, Aaron Boodman, Michael Nordman, Jian Li, Dmitry Titov, Ian Hickson, Darin Fisher, Sam Weinig, Adrian Bateman and Julian Reschke.
Thanks to the W3C WebApps WG, and to participants on the public-webapps@w3.org listserv
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
with class="example"
,
like this:
Informative notes begin with the word “Note”
and are set apart from the normative text
with class="note"
,
like this:
Note, this is an informative note.
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.
[Exposed =(Window ,Worker ),Serializable ]interface {
Blob (
constructor optional sequence <BlobPart >blobParts ,optional BlobPropertyBag = {});
options readonly attribute unsigned long long size ;readonly attribute DOMString type ; // slice Blob into byte-ranged chunksBlob slice (optional [Clamp ]long long ,
start optional [Clamp ]long long ,
end optional DOMString ); // read from the Blob. [
contentType NewObject ]ReadableStream stream (); [NewObject ]Promise <USVString >text (); [NewObject ]Promise <ArrayBuffer >arrayBuffer (); [NewObject ]Promise <Uint8Array >bytes (); };enum {
EndingType ,
"transparent" };
"native" dictionary {
BlobPropertyBag DOMString type = "";EndingType endings = "transparent"; };typedef (BufferSource or Blob or USVString ); [
BlobPart Exposed =(Window ,Worker ),Serializable ]interface :
File Blob {(
constructor sequence <BlobPart >fileBits ,USVString fileName ,optional FilePropertyBag = {});
options readonly attribute DOMString name ;readonly attribute long long lastModified ; };dictionary :
FilePropertyBag BlobPropertyBag {long long lastModified ; }; [Exposed =(Window ,Worker ),Serializable ]interface {
FileList getter File ?item (unsigned long index );readonly attribute unsigned long length ; }; [Exposed =(Window ,Worker )]interface :
FileReader EventTarget {constructor (); // async read methodsundefined readAsArrayBuffer (Blob );
blob undefined readAsBinaryString (Blob );
blob undefined readAsText (Blob ,
blob optional DOMString );
encoding undefined readAsDataURL (Blob );
blob undefined abort (); // statesconst unsigned short = 0;
EMPTY const unsigned short = 1;
LOADING const unsigned short = 2;
DONE readonly attribute unsigned short readyState ; // File or Blob datareadonly attribute (DOMString or ArrayBuffer )?result ;readonly attribute DOMException ?error ; // event handler content attributesattribute EventHandler onloadstart ;attribute EventHandler onprogress ;attribute EventHandler onload ;attribute EventHandler onabort ;attribute EventHandler onerror ;attribute EventHandler onloadend ; }; [Exposed =(DedicatedWorker ,SharedWorker )]interface {
FileReaderSync (); // Synchronously return strings
constructor ArrayBuffer readAsArrayBuffer (Blob );
blob DOMString readAsBinaryString (Blob );
blob DOMString readAsText (Blob ,
blob optional DOMString );
encoding DOMString readAsDataURL (Blob ); }; [
blob Exposed =(Window ,DedicatedWorker ,SharedWorker )]partial interface URL {static DOMString createObjectURL ((Blob or MediaSource ));
obj static undefined revokeObjectURL (DOMString ); };
url
loadstart
to be dispatched synchronously,
to align with XMLHttpRequest behavior. [Issue #119] ↵In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.
In all current engines.