-
Notifications
You must be signed in to change notification settings - Fork 45
/
index.bs
1847 lines (1429 loc) · 80.5 KB
/
index.bs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<pre class="metadata">
Indent: 2
Title: File API
Shortname: FileAPI
Level: none
Group: webapps
Editor: Marijn Kruisselbrink, Google, [email protected], w3cid 72440
Former Editor: Arun Ranganathan, Mozilla Corporation, http://arunranga.com/, [email protected], w3cid 37240
Prepare For TR: true
Status: ED
ED: https://w3c.github.io/FileAPI/
TR: https://www.w3.org/TR/FileAPI/
Repository: w3c/FileAPI
!Tests: <a href=https://github.com/web-platform-tests/wpt/tree/master/FileAPI>web-platform-tests FileAPI/</a> (<a href=https://github.com/web-platform-tests/wpt/labels/FileAPI>ongoing work</a>)
Abstract: This specification provides an API for representing file objects in web applications,
as well as programmatically selecting them and accessing their data. This includes:
* A {{FileList}} interface, which represents an array of individually selected files from the underlying system. The user interface for selection can be invoked via <code><input type="file"></code>, i.e. when the input element is in the <code>File Upload</code> state [[HTML]].
* A {{Blob}} interface, which represents immutable raw binary data, and allows access to ranges of bytes within the {{Blob}} object as a separate {{Blob}}.
* A {{File}} interface, which includes readonly informational attributes about a file such as its name and the date of the last modification (on disk) of the file.
* A {{FileReader}} interface, which provides methods to read a {{File}} or a {{Blob}}, and an event model to obtain the results of these reads.
* A <a section href="#url">URL scheme</a> 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.
[[#requirements]] covers the motivation behind this specification.
This API is designed to be used in conjunction with other APIs and elements on the web platform, notably:
{{XMLHttpRequest}} (e.g. with an overloaded {{XMLHttpRequest/send()}} method for {{File}} or {{Blob}} arguments),
{{Worker/postMessage(message, options)|postMessage()}},
{{DataTransfer}} (part of the drag and drop API defined in [[HTML]])
and Web Workers.
Additionally, it should be possible to programmatically obtain a list of files from the <{input}> element
when it is in the <code>File Upload</code> state [[HTML]].
These kinds of behaviors are defined in the appropriate affiliated specifications.
Status Text: Previous discussion of this specification has taken place on two other mailing lists: <a href="mailto:[email protected]">[email protected]</a> (<a href="http://lists.w3.org/Archives/Public/public-webapps/">archive</a>) and <a href="mailto:[email protected]">[email protected]</a> (<a href="http://lists.w3.org/Archives/Public/public-webapi/">archive</a>). Ongoing discussion will be on the <a href="mailto:[email protected]">[email protected]</a> mailing list.
This draft consists of changes made to the previous Last Call Working Draft. Please send comments to the <a href="mailto:[email protected]">[email protected]</a> as described above. You can see Last Call Feedback on the W3C Wiki: <a href="http://www.w3.org/wiki/Webapps/LCWD-FileAPI-20130912">http://www.w3.org/wiki/Webapps/LCWD-FileAPI-20130912</a>
An [implementation report](https://wpt.fyi/results/FileAPI) is automatically generated from the test suite.
Translate Ids: dictdef-blobpropertybag dfn-BlobPropertyBag, dictdef-filepropertybag dfn-FilePropertyBag, filereadersync dfn-FileReaderSync, filelist dfn-filelist, filereader dfn-filereader, file dfn-file, blob dfn-Blob, blob-section blob, file-section file
Markup Shorthands: css no, markdown yes
</pre>
<pre class="link-defaults">
spec: dom
type:interface
text:Document
spec: html
type: element
text: a
text: iframe
type: element-attr
text: download; for: a
spec: infra
type: dfn
text: list
text: string
text: code point
spec: streams
type: dfn
text: chunk
spec: url
type: dfn
text: url; for:/
type: interface
text: URL
</pre>
<pre class="anchors">
spec: mimesniff; urlPrefix: https://mimesniff.spec.whatwg.org/
type: dfn
text: parsable mime type
spec: ecma-262; urlPrefix: http://tc39.github.io/ecma262/
type: interface
text: Array; url: sec-array-constructor
text: Date; url: sec-date-constructor
spec: media-source; urlPrefix: http://w3c.github.io/media-source/
type: interface
text: MediaSource; url: #mediasource
</pre>
# Introduction # {#intro}
*This section is informative.*
Web applications should have the ability to manipulate as wide as possible a range of user input,
including files that a user may wish to upload to a remote server or manipulate inside a rich web application.
This specification defines the basic representations for files,
lists of files,
errors raised by access to files,
and programmatic ways to read files.
Additionally, this specification also defines an interface that represents "raw data"
which can be asynchronously processed on the main thread of conforming user agents.
The interfaces and API defined in this specification can be used with other interfaces and APIs exposed to the web platform.
The {{File}} interface represents file data typically obtained from the underlying file system,
and the {{Blob}} interface
("Binary Large Object" - a name originally introduced to web APIs in <a href="https://developers.google.com/gears/?csw=1">Google Gears</a>)
represents immutable raw data.
{{File}} or {{Blob}} reads should happen asynchronously on the main thread,
with an optional synchronous API used within threaded web applications.
An asynchronous API for reading files prevents blocking and UI "freezing" on a user agent's main thread.
This specification defines an asynchronous API based on an *event model*
to read and access a {{File}} or {{Blob}}’s data.
A {{FileReader}} object provides asynchronous read methods to access that file's data
through event handler content attributes and the firing of events.
The use of events and event handlers allows separate code blocks the ability
to monitor the *progress of the read*
(which is particularly useful for remote drives or mounted drives,
where file access performance may vary from local drives)
and error conditions that may arise during reading of a file.
An example will be illustrative.
<div class="example">
In the example below, different code blocks handle progress, error, and success conditions.
<pre highlight="js">
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
}
}
</pre>
</div>
# Terminology and Algorithms # {#terminology}
When this specification says to <dfn id="terminate-an-algorithm" lt="terminate an algorithm|terminate this algorithm">terminate an algorithm</dfn>
the user agent must terminate the algorithm after finishing the step it is on.
Asynchronous <a>read methods</a> defined in this specification may return before the algorithm in question is terminated,
and can be terminated by an {{FileReader/abort()}} call.
The algorithms and steps in this specification use the following mathematical operations:
* max(a,b) returns the maximum of a and b,
and is always performed on integers as they are defined in WebIDL [[WebIDL]];
in the case of max(6,4) the result is 6.
This operation is also defined in ECMAScript [[!ECMA-262]].
* min(a,b) returns the minimum of a and b,
and is always performed on integers as they are defined in WebIDL [[WebIDL]];
in the case of min(6,4) the result is 4.
This operation is also defined in ECMAScript [[ECMA-262]].
* Mathematical comparisons such as < (less than), ≤ (less than or equal to), and > (greater than) are as in ECMAScript [[ECMA-262]].
The term <dfn id="UnixEpoch">Unix Epoch</dfn> 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 "<code>0</code>" in ECMA-262 [[ECMA-262]].
<div algorithm>
The <dfn export>slice blob</dfn> algorithm given a {{Blob}} <var>blob</var>, <var>start</var>,
<var>end</var>, and <var>contentType</var> is used to refer to the following
steps and returns a new {{Blob}} containing the bytes ranging from the <var>start</var> parameter
up to but not including the <var>end</var> parameter. It must act as follows:
1. Let <var>originalSize</var> be <var>blob</var>'s {{Blob/size}}.
1. The <var>start</var> parameter, if non-null, is a value for the start point of a <a>slice blob</a>
call, and must be treated as a byte-order position, with the zeroth position representing the
first byte. User agents must normalize <var>start</var> according to the following:
<ol type="a">
<li>If <var>start</var> is null, let <var>relativeStart</var> be 0.
<li>If <var>start</var> is negative, let <var>relativeStart</var> be
<code>max((<var>originalSize</var> + <var>start</var>), 0)</code>.
<li>Otherwise, let <var>relativeStart</var> be
<code>min(<var>start</var>, <var>originalSize</var>)</code>.
</ol>
1. The <var>end</var> parameter, if non-null. is a value for the end point of a <a>slice blob</a>
call. User agents must normalize <var>end</var> according to the following:
<ol type="a">
<li>If <var>end</var> is null, let <var>relativeEnd</var> be <var>originalSize</var>.
<li>If <var>end</var> is negative, let <var>relativeEnd</var> be
<code>max((<var>originalSize</var> + <var>end</var>), 0)</code>.
<li>Otherwise, let <var>relativeEnd</var> be
<code>min(<var>end</var>, <var>originalSize</var>)</code>.
</ol>
1. The <var>contentType</var> parameter, if non-null, is used to set the ASCII-encoded string in
lower case representing the media type of the {{Blob}}. User agents must normalize
<var>contentType</var> according to the following:
<ol type="a">
<li>If <var>contentType</var> is null, let <var>relativeContentType</var> be set to the empty
string.
<li>Otherwise, let <var>relativeContentType</var> be set to <var>contentType</var> and run the
substeps below:
1. If <var>relativeContentType</var> contains any characters outside the range of U+0020 to
U+007E, then set <var>relativeContentType</var> to the empty string and return from these
substeps.
2. Convert every character in <var>relativeContentType</var> to [=ASCII lowercase=].
</ol>
1. Let <var>span</var> be <code>max((<var>relativeEnd</var> - <var>relativeStart</var>), 0)</code>.
1. Return a new {{Blob}} object <var>S</var> with the following characteristics:
<ol type="a">
<li><var>S</var> refers to <var>span</var> consecutive <a>byte</a>s from <var>blob</var>'s
associated <a>byte</a> sequence, beginning with the <a>byte</a> at byte-order position
<var>relativeStart</var>.
<li><var>S</var>.{{Blob/size}} = <var>span</var>.
<li><var>S</var>.{{Blob/type}} = <var>relativeContentType</var>.
</ol>
</div>
<!--
████████ ██ ███████ ████████
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
████████ ██ ██ ██ ████████
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
████████ ████████ ███████ ████████
-->
# The Blob Interface and Binary Data # {#blob-section}
A {{Blob}} object refers to a <a>byte</a> sequence,
and has a {{Blob/size}} attribute which is the total number of bytes in the byte sequence,
and a {{Blob/type}} attribute,
which is an ASCII-encoded string in lower case representing the media type of the <a>byte</a> sequence.
Each {{Blob}} must have an internal <dfn id="snapshot-state" for=Blob>snapshot state</dfn>,
which must be initially set to the state of the underlying storage,
if any such underlying storage exists.
Further normative definition of <a>snapshot state</a> can be found for {{File}}s.
<xmp class="idl">
[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 chunks
Blob slice(optional [Clamp] long long start,
optional [Clamp] long long end,
optional DOMString contentType);
// read from the Blob.
[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;
</xmp>
{{Blob}} objects are [=serializable objects=]. Their [=serialization steps=],
given |value| and |serialized|, are:
1. Set |serialized|.\[[SnapshotState]] to |value|'s [=snapshot state=].
2. Set |serialized|.\[[ByteSequence]] to |value|'s underlying byte sequence.
Their [=deserialization step=], given |serialized| and |value|, are:
1. Set |value|'s [=snapshot state=] to |serialized|.\[[SnapshotState]].
2. Set |value|'s underlying byte sequence to |serialized|.\[[ByteSequence]].
<div algorithm="get stream">
A {{Blob}} |blob| has an associated <dfn export for=Blob>get stream</dfn> algorithm,
which runs these steps:
1. Let |stream| be a [=new=] {{ReadableStream}} created in |blob|'s [=relevant Realm=].
1. [=ReadableStream/set up with byte reading support|Set up=] |stream| with byte reading support.
1. Run the following steps [=in parallel=]:
1. While not all bytes of |blob| have been read:
1. Let |bytes| be the [=byte sequence=] that results from reading a [=chunk=] from |blob|, or
failure if a chunk cannot be read.
1. [=Queue a global task=] on the [=file reading task source=] given |blob|'s
[=relevant global object=] to perform the following steps:
1. If |bytes| is failure, then [=ReadableStream/error=] |stream| with a [=failure reason=] and
abort these steps.
1. Let |chunk| be a new {{Uint8Array}} wrapping an {{ArrayBuffer}} containing |bytes|. If
creating the {{ArrayBuffer}} throws an exception, then [=ReadableStream/error=] |stream|
with that exception and abort these steps.
1. [=ReadableStream/Enqueue=] |chunk| in |stream|.
Issue: We need to specify more concretely what reading from a Blob actually does,
what possible errors can happen, perhaps something about chunk sizes, etc.
1. Return |stream|.
</div>
## Constructors ## {#constructorBlob}
<div algorithm="blob-constructor">
The {{Blob()}} constructor can be invoked with zero or more parameters.
When the {{Blob()}} constructor is invoked,
user agents must run the following steps:
1. If invoked with zero parameters,
return a new {{Blob}} object consisting of 0 bytes,
with {{Blob/size}} set to 0,
and with {{Blob/type}} set to the empty string.
1. Let |bytes| be the result of [=processing blob parts=] given {{blobParts}} and {{Blob/Blob(blobParts, options)/options}}.
1. If the {{BlobPropertyBag/type}} member of the {{Blob/Blob(blobParts, options)/options}} argument is not the empty string,
run the following sub-steps:
1. Let |t| be the {{BlobPropertyBag/type}} dictionary member.
If |t| contains any characters outside the range U+0020 to U+007E,
then set |t| to the empty string and return from these substeps.
1. Convert every character in |t| to [=ASCII lowercase=].
1. Return a {{Blob}} object referring to |bytes| as its associated <a>byte</a> sequence,
with its {{Blob/size}} set to the length of |bytes|,
and its {{Blob/type}} set to the value of |t| from the substeps above.
</div>
### Constructor Parameters ### {#constructorParams}
The {{Blob()}} constructor can be invoked with the parameters below:
<dl>
<dt>A <dfn id="dfn-blobParts" argument for="Blob/Blob(blobParts, options)"><code>blobParts</code></dfn> <code>sequence</code>
<dd>which takes any number of the following types of elements, and in any order:
* {{BufferSource}} elements.
* {{Blob}} elements.
* {{USVString}} elements.
<dt id="dfn-BlobPropertyBagMembers">An *optional* {{BlobPropertyBag}}
<dd>which takes these optional members:
* <dfn id="dfn-BPtype" dict-member for="BlobPropertyBag">type</dfn>,
the ASCII-encoded string in lower case representing the media type of the {{Blob}}.
Normative conditions for this member are provided in the [[#constructorBlob]].
* <dfn dict-member for="BlobPropertyBag">endings</dfn>,
an enum which can take the values {{"transparent"}} or {{"native"}}.
By default this is set to {{"transparent"}}. If set to {{"native"}},
[=convert line endings to native|line endings will be converted to native=]
in any {{USVString}} elements in {{blobParts}}.
</dl>
<div algorithm="process-blob-parts">
To <dfn lt="process blob parts|processing blob parts">process blob parts</dfn> given a sequence of {{BlobPart}}'s |parts|
and {{BlobPropertyBag}} |options|,
run the following steps:
1. Let |bytes| be an empty sequence of bytes.
1. For each |element| in |parts|:
1. If |element| is a {{USVString}}, run the following substeps:
1. Let |s| be |element|.
1. If the {{BlobPropertyBag/endings}} member of |options| is {{"native"}},
set |s| to the result of [=converting line endings to native=] of |element|.
1. Append the result of [=UTF-8 encoding=] |s| to |bytes|.
Note: The algorithm from WebIDL [[WebIDL]] replaces unmatched surrogates in an invalid utf-16 string
with U+FFFD replacement characters.
Scenarios exist when the {{Blob}} constructor may result in some data loss
due to lost or scrambled character sequences.
1. If |element| is a {{BufferSource}}, <a lt="get a copy of the buffer source">get
a copy of the bytes held by the buffer source</a>, and append those bytes to |bytes|.
1. If |element| is a {{Blob}},
append the bytes it represents to |bytes|.
Note: The {{Blob/type}} of the {{Blob}} array element is ignored and will not affect {{Blob/type}} of returned
{{Blob}} object.
1. Return |bytes|.
</div>
<div algorithm="convert-line-endings-to-native">
To <dfn lt="convert line endings to native|converting line endings to native">
convert line endings to native</dfn> in a [=string=] |s|,
run the following steps:
1. Let |native line ending| be the [=code point=] U+000A LF.
1. 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.
1. Set |result| to the empty [=string=].
1. Let |position| be a [=position variable=] for |s|,
initially pointing at the start of |s|.
1. Let |token| be the result of [=collecting a sequence of code points=]
that are not equal to U+000A LF or U+000D CR
from |s| given |position|.
1. Append |token| to |result|.
1. While |position| is not past the end of |s|:
1. If the [=code point=] at |position| within |s| equals U+000D CR:
1. Append |native line ending| to |result|.
1. Advance |position| by 1.
1. If |position| is not past the end of |s|
and the [=code point=] at |position| within |s| equals U+000A LF
advance |position| by 1.
1. Otherwise if the [=code point=] at |position| within |s| equals U+000A LF,
advance |position| by 1 and append |native line ending| to |result|.
1. Let |token| be the result of [=collecting a sequence of code points=]
that are not equal to U+000A LF or U+000D CR
from |s| given |position|.
1. Append |token| to |result|.
1. Return |result|.
</div>
<div class="example">
Examples of constructor usage follow.
<pre class="lang-javascript">
// 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]);
</pre>
</div>
## Attributes ## {#attributes-blob}
<dl dfn-type="attribute" dfn-for="Blob">
<dt><dfn id="dfn-size">size</dfn>
<dd>Returns the size of the <a>byte</a> sequence in number of bytes.
On getting, conforming user agents must return the total number of bytes that can be read by a {{FileReader}} or {{FileReaderSync}} object,
or 0 if the {{Blob}} has no bytes to be read.
<dt><dfn id="dfn-type">type</dfn>
<dd>The ASCII-encoded string in lower case representing the media type of the {{Blob}}.
On getting, user agents must return the type of a {{Blob}}
as an ASCII-encoded string in lower case,
such that when it is converted to a <a>byte</a> sequence,
it is a <a>parsable MIME type</a>,
or the empty string – 0 bytes – if the type cannot be determined.
The {{Blob/type}} attribute can be set by the web application itself through constructor invocation
and through the {{Blob/slice()}} call;
in these cases, further normative conditions for this attribute are in [[#constructorBlob]],
[[#file-constructor]],
and [[#slice-method-algo]] respectively.
User agents can also determine the {{Blob/type}} of a {{Blob}},
especially if the <a>byte</a> sequence is from an on-disk file;
in this case, further normative conditions are in the <a>file type guidelines</a>.
Note: The type <var ignore>t</var> of a {{Blob}} is considered a <a>parsable MIME type</a>,
if performing the <a>parse a MIME type</a> 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 {{Blob/type}} attribute informs the [=package data=] algorithm
and determines the `Content-Type` header when [=/fetching=] [=blob URLs=].
</dl>
## Methods and Parameters ## {#methodsandparams-blob}
### The {{Blob/slice()}} method ### {#slice-method-algo}
<div algorithm>
The <dfn id="dfn-slice" method for=Blob lt="slice(start, end, contentType), slice(start, end), slice(start), slice()">slice()</dfn> method
returns a new {{Blob}} object with bytes ranging from the optional <var>start</var> parameter
up to but not including the optional <var>end</var> parameter, and with a {{Blob/type}} attribute
that is the value of the optional <var>contentType</var> parameter. It must act as follows:
1. Let <var>sliceStart</var>, <var>sliceEnd</var>, and <var>sliceContentType</var> be null.
1. If <var>start</var> is given, set <var>sliceStart</var> to <var>start</var>.
1. If <var>end</var> is given, set <var>sliceEnd</var> to <var>end</var>.
1. If <var>contentType</var> is given, set <var>sliceContentType</var> to <var>contentType</var>.
1. Return the result of <a>slice blob</a> given <a>this</a>, <var>sliceStart</var>,
<var>sliceEnd</var>, and <var>sliceContentType</var>.
<div class="example">
The examples below illustrate the different types of {{slice()}} calls possible. Since the
{{File}} interface inherits from the {{Blob}} interface, examples are based on the use of the {{File}} interface.
<pre class="lang-javascript">
// 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");
}
</pre>
</div>
</div>
### The {{Blob/stream()}} method ### {#stream-method-algo}
The <dfn method for=Blob>stream()</dfn> method, when invoked, must return
the result of calling [=get stream=] on [=this=].
### The {{Blob/text()}} method ### {#text-method-algo}
The <dfn method for=Blob>text()</dfn> method, when invoked, must run these steps:
1. Let |stream| be the result of calling [=get stream=] on [=this=].
1. Let |reader| be the result of [=get a reader|getting a reader=] from |stream|.
If that threw an exception, return a new promise rejected with that exception.
1. Let |promise| be the result of [=read all bytes|reading all bytes=] from |stream| with |reader|.
1. 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 {{FileReader/readAsText()}} to align better
with the behavior of {{Body/text()|Fetch's text()}}. Specifically this method will always
use UTF-8 as encoding, while {{FileReader}} can use a different encoding depending on
the blob's type and passed in encoding name.
### The {{Blob/arrayBuffer()}} method ### {#arraybuffer-method-algo}
The <dfn method for=Blob>arrayBuffer()</dfn> method, when invoked, must run these steps:
1. Let |stream| be the result of calling [=get stream=] on [=this=].
1. Let |reader| be the result of [=get a reader|getting a reader=] from |stream|.
If that threw an exception, return a new promise rejected with that exception.
1. Let |promise| be the result of [=read all bytes|reading all bytes=] from |stream| with |reader|.
1. Return the result of transforming |promise| by a fulfillment handler that returns
a new {{ArrayBuffer}} whose contents are its first argument.
### The {{Blob/bytes()}} method ### {#bytes-method-algo}
The <dfn method for=Blob>bytes()</dfn> method, when invoked, must run these steps:
1. Let |stream| be the result of calling [=get stream=] on [=this=].
1. Let |reader| be the result of [=get a reader|getting a reader=] from |stream|.
If that threw an exception, return a new promise rejected with that exception.
1. Let |promise| be the result of [=read all bytes|reading all bytes=] from |stream| with |reader|.
1. Return the result of transforming |promise| by a fulfillment handler that returns
a new {{Uint8Array}} wrapping an {{ArrayBuffer}} containing its first argument.
<!--
████████ ████ ██ ████████
██ ██ ██ ██
██ ██ ██ ██
██████ ██ ██ ██████
██ ██ ██ ██
██ ██ ██ ██
██ ████ ████████ ████████
-->
# The File Interface # {#file-section}
A {{File}} object is a {{Blob}} object with a {{File/name}} attribute, which is a string;
it can be created within the web application via a constructor,
or is a reference to a <a>byte</a> sequence from a file from the underlying (OS) file system.
If a {{File}} object is a reference to a <a>byte</a> sequence originating from a file on disk,
then its <a>snapshot state</a> should be set to the state of the file on disk at the time the {{File}} object is created.
Note: This is a non-trivial requirement to implement for user agents,
and is thus not a *must* but a *should* [[RFC2119]].
User agents should endeavor to have a {{File}} object's <a>snapshot state</a>
set to the state of the underlying storage on disk at the time the reference is taken.
If the file is modified on disk following the time a reference has been taken,
the {{File}}'s <a>snapshot state</a> will differ from the state of the underlying storage.
User agents may use modification time stamps and other mechanisms to maintain <a>snapshot state</a>,
but this is left as an implementation detail.
When a {{File}} object refers to a file on disk,
user agents must return the {{Blob/type}} of that file,
and must follow the <dfn export>file type guidelines</dfn> below:
* User agents must return the {{Blob/type}} as an ASCII-encoded string in lower case,
such that when it is converted to a corresponding byte sequence,
it is a <a>parsable MIME type</a>,
or the empty string – 0 bytes – if the type cannot be determined.
* When the file is of type <code>text/plain</code>
user agents must NOT append a charset parameter to the <i>dictionary of parameters</i> portion of the media type [[!MIMESNIFF]].
* User agents must not attempt heuristic determination of encoding,
including statistical methods.
<pre class="idl">
[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;
};
</pre>
{{File}} objects are [=serializable objects=]. Their [=serialization steps=],
given |value| and |serialized|, are:
1. Set |serialized|.\[[SnapshotState]] to |value|'s [=snapshot state=].
2. Set |serialized|.\[[ByteSequence]] to |value|'s underlying byte sequence.
3. Set |serialized|.\[[Name]] to the value of |value|'s {{File/name}} attribute.
4. Set |serialized|.\[[LastModified]] to the value of |value|'s {{File/lastModified}} attribute.
Their [=deserialization steps=], given |value| and |serialized|, are:
1. Set |value|'s [=snapshot state=] to |serialized|.\[[SnapshotState]].
2. Set |value|'s underlying byte sequence to |serialized|.\[[ByteSequence]].
3. Initialize the value of |value|'s {{File/name}} attribute to |serialized|.\[[Name]].
4. Initialize the value of |value|'s {{File/lastModified}} attribute to
|serialized|.\[[LastModified]].
## Constructor ## {#file-constructor}
<div algorithm="file-constructor">
The {{File}} constructor is invoked with two or three parameters,
depending on whether the optional dictionary parameter is used.
When the {{File()}} constructor is invoked,
user agents must run the following steps:
1. Let |bytes| be the result of [=processing blob parts=] given {{fileBits}}
and {{File/File(fileBits, fileName, options)/options}}.
2. Let |n| be the {{fileName}} 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 <a>byte</a> sequences.
3. Process {{FilePropertyBag}} dictionary argument by running the following substeps:
1. If the {{BlobPropertyBag/type}} member is provided and is not the empty string,
let |t| be set to the {{BlobPropertyBag/type}} dictionary member.
If |t| contains any characters outside the range U+0020 to U+007E,
then set |t| to the empty string and return from these substeps.
2. Convert every character in |t| to [=ASCII lowercase=].
3. If the {{FilePropertyBag/lastModified}} member is provided,
let |d| be set to the {{FilePropertyBag/lastModified}} dictionary member.
If it is not provided,
set |d| to the current date and time
represented as the number of milliseconds since the <a>Unix Epoch</a>
(which is the equivalent of <code>Date.now()</code> [[ECMA-262]]).
Note: Since ECMA-262 {{Date}} objects convert to <code>long long</code> values
representing the number of milliseconds since the <a>Unix Epoch</a>,
the {{FilePropertyBag/lastModified}} member could be a {{Date}} object [[ECMA-262]].
4. Return a new {{File}} object |F| such that:
2. |F| refers to the |bytes| <a>byte</a> sequence.
3. |F|.{{Blob/size}} is set to the number of total bytes in |bytes|.
4. |F|.{{File/name}} is set to |n|.
5. |F|.{{Blob/type}} is set to |t|.
6. |F|.{{File/lastModified}} is set to |d|.
</div>
### Constructor Parameters ### {#file-constructor-params}
The {{File()}} constructor can be invoked with the parameters below:
<dl>
<dt>A <dfn id="dfn-fileBits" argument for="File/File(fileBits, fileName, options)"><code>fileBits</code></dfn> <code>sequence</code>
<dd>which takes any number of the following elements, and in any order:
* {{BufferSource}} elements.
* {{Blob}} elements, which includes {{File}} elements.
* {{USVString}} elements.
<dt>A <dfn id="dfn-fileName" argument for="File/File(fileBits, fileName, options)"><code>fileName</code></dfn> parameter
<dd>A {{USVString}} parameter representing the name of the file;
normative conditions for this constructor parameter can be found in [[#file-constructor]].
<dt id="def-Properties">An optional {{FilePropertyBag}} dictionary
<dd>which in addition to the <a href="#dfn-BlobPropertyBagMembers">members</a> of
{{BlobPropertyBag}} takes one member:
* An optional <dfn dict-member for=FilePropertyBag id="dfn-FPdate">lastModified</dfn> member,
which must be a <code>long long</code>;
normative conditions for this member are provided in [[#file-constructor]].
</dl>
## Attributes ## {#file-attrs}
<dl dfn-type=attribute dfn-for=File>
<dt><dfn id="dfn-name">name</dfn>
<dd>The name of the file.
On getting, this must return the name of the file as a string.
There are numerous file name variations and conventions used by different underlying OS file systems;
this is merely the name of the file, without path information.
On getting, if user agents cannot make this information available,
they must return the empty string.
If a {{File}} object is created using a constructor,
further normative conditions for this attribute are found in [[#file-constructor]].
<dt><dfn id="dfn-lastModified">lastModified</dfn>
<dd>The last modified date of the file.
On getting, if user agents can make this information available,
this must return a <code>long long</code> set to the time the file was last modified
as the number of milliseconds since the <a>Unix Epoch</a>.
If the last modification date and time are not known,
the attribute must return the current date and time
as a <code>long long</code> representing the number of milliseconds since the <a>Unix Epoch</a>;
this is equivalent to <code class="lang-javascript">Date.now()</code> [[ECMA-262]].
If a {{File}} object is created using a constructor,
further normative conditions for this attribute are found in [[#file-constructor]].
</dl>
The {{File}} interface is available on objects that expose an attribute of type {{FileList}};
these objects are defined in HTML [[HTML]].
The {{File}} interface, which inherits from {{Blob}}, is immutable,
and thus represents file data that can be read into memory at the time a <a>read operation</a> is initiated.
User agents must process reads on files that no longer exist at the time of read as <a lt="file read error">errors</a>,
throwing a {{NotFoundError}} exception
if using a {{FileReaderSync}} on a Web Worker [[Workers]]
or firing an {{error!!event}} event
with the {{error!!attribute}} attribute returning a {{NotFoundError}}.
<div class="example">
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.
<pre class="lang-javascript">
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})
...
</pre>
</div>
# The FileList Interface # {#filelist-section}
Note: The {{FileList}} interface should be considered "at risk"
since the general trend on the Web Platform is to replace such interfaces
with the {{Array}} platform object in ECMAScript [[ECMA-262]].
In particular, this means syntax of the sort <code class="lang-javascript">filelist.item(0)</code> is at risk;
most other programmatic use of {{FileList}} is unlikely to be affected by the eventual migration to an {{Array}} type.
This interface is a list of {{File}} objects.
<pre class="idl">
[Exposed=(Window,Worker), Serializable]
interface FileList {
getter File? item(unsigned long index);
readonly attribute unsigned long length;
};
</pre>
{{FileList}} objects are [=serializable objects=]. Their [=serialization steps=],
given |value| and |serialized|, are:
1. Set |serialized|.\[[Files]] to an empty [=list=].
2. For each |file| in |value|, append the [=sub-serialization=] of |file| to
|serialized|.\[[Files]].
Their [=deserialization step=], given |serialized| and |value|, are:
1. [=list/For each=] |file| of |serialized|.\[[Files]], add the [=sub-deserialization=] of |file| to |value|.
<div class="example">
Sample usage typically involves DOM access to the <code><input type="file"></code> element within a form,
and then accessing selected files.
<pre class="lang-javascript">
// 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
}
</pre>
</div>
## Attributes ## {#attributes-filelist}
<dl>
<dt><dfn attribute for=FileList id="dfn-length">length</dfn>
<dd>must return the number of files in the {{FileList}} object.
If there are no files, this attribute must return 0.
</dl>
## Methods and Parameters ## {#filelist-methods-params}
<dl>
<dt><dfn method for=FileList id="dfn-item">item(index)</dfn>
<dd>must return the |index|th {{File}} object in the {{FileList}}.
If there is no |index|th {{File}} object in the {{FileList}},
then this method must return <code>null</code>.
<dfn argument for="FileList/item(index)" id="dfn-index">index</dfn> must be treated by user agents
as value for the position of a {{File}} object in the {{FileList}},
with 0 representing the first file.
<a>Supported property indices</a> are the numbers in the range zero
to one less than the number of {{File}} objects represented by the {{FileList}} object.
If there are no such {{File}} objects,
then there are no supported property indices.
</dl>
Note: The {{HTMLInputElement}} interface has a readonly attribute of type {{FileList}},
which is what is being accessed in the above example.
Other interfaces with a readonly attribute of type {{FileList}} include the {{DataTransfer}} interface.
# Reading Data # {#reading-data-section}
## The File Reading Task Source ## {#blobreader-task-source}
This specification defines a new generic [=task source=] called the
<dfn id="fileReadingTaskSource">file reading task source</dfn>,
which is used for all [=queue a task|tasks that are queued=] in this specification
to read byte sequences associated with {{Blob}} and {{File}} objects.
It is to be used for features that trigger in response to asynchronously reading binary data.
## The {{FileReader}} API ## {#APIASynch}
<pre class="idl">
[Exposed=(Window,Worker)]
interface FileReader: EventTarget {
constructor();
// async read methods
undefined readAsArrayBuffer(Blob blob);
undefined readAsBinaryString(Blob blob);
undefined readAsText(Blob blob, optional DOMString encoding);
undefined readAsDataURL(Blob blob);
undefined abort();
// states
const unsigned short EMPTY = 0;
const unsigned short LOADING = 1;
const unsigned short DONE = 2;
readonly attribute unsigned short readyState;
// File or Blob data
readonly attribute (DOMString or ArrayBuffer)? result;
readonly attribute DOMException? error;
// event handler content attributes
attribute EventHandler onloadstart;
attribute EventHandler onprogress;
attribute EventHandler onload;
attribute EventHandler onabort;
attribute EventHandler onerror;
attribute EventHandler onloadend;
};
</pre>
A {{FileReader}} has an associated <dfn for=FileReader>state</dfn>,
that is `"empty"`, `"loading"`, or `"done"`. It is initially `"empty"`.
A {{FileReader}} has an associated <dfn for=FileReader>result</dfn>
(`null`, a {{DOMString}} or an {{ArrayBuffer}}). It is initially `null`.
A {{FileReader}} has an associated <dfn for=FileReader>error</dfn>
(`null` or a {{DOMException}}). It is initially `null`.
The <dfn constructor for=FileReader id=filereaderConstrctr>FileReader()</dfn> constructor,
when invoked, must return a new {{FileReader}} object.
The <dfn attribute for=FileReader>readyState</dfn> attribute's getter,
when invoked, switches on [=this=]'s [=FileReader/state=]
and runs the associated step:
: `"empty"`
:: Return {{EMPTY}}
: `"loading"`
:: Return {{LOADING}}
: `"done"`
:: Return {{DONE}}
The <dfn attribute for=FileReader>result</dfn> attribute's getter,
when invoked, must return [=this=]'s [=FileReader/result=].
The <dfn attribute for=FileReader>error</dfn> attribute's getter,
when invoked, must return [=this=]'s [=FileReader/error=].