forked from avrios/ng-file-upload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileAPI.js
4313 lines (3612 loc) · 102 KB
/
FileAPI.js
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
/*! FileAPI 2.0.7 - BSD | git://github.com/mailru/FileAPI.git
* FileAPI — a set of javascript tools for working with files. Multiupload, drag'n'drop and chunked file upload. Images: crop, resize and auto orientation by EXIF.
*/
/*
* JavaScript Canvas to Blob 2.0.5
* https://github.com/blueimp/JavaScript-Canvas-to-Blob
*
* Copyright 2012, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*
* Based on stackoverflow user Stoive's code snippet:
* http://stackoverflow.com/q/4998908
*/
/*jslint nomen: true, regexp: true */
/*global window, atob, Blob, ArrayBuffer, Uint8Array */
(function (window) {
'use strict';
var CanvasPrototype = window.HTMLCanvasElement &&
window.HTMLCanvasElement.prototype,
hasBlobConstructor = window.Blob && (function () {
try {
return Boolean(new Blob());
} catch (e) {
return false;
}
}()),
hasArrayBufferViewSupport = hasBlobConstructor && window.Uint8Array &&
(function () {
try {
return new Blob([new Uint8Array(100)]).size === 100;
} catch (e) {
return false;
}
}()),
BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||
window.MozBlobBuilder || window.MSBlobBuilder,
dataURLtoBlob = (hasBlobConstructor || BlobBuilder) && window.atob &&
window.ArrayBuffer && window.Uint8Array && function (dataURI) {
var byteString,
arrayBuffer,
intArray,
i,
mimeString,
bb;
if (dataURI.split(',')[0].indexOf('base64') >= 0) {
// Convert base64 to raw binary data held in a string:
byteString = atob(dataURI.split(',')[1]);
} else {
// Convert base64/URLEncoded data component to raw binary data:
byteString = decodeURIComponent(dataURI.split(',')[1]);
}
// Write the bytes of the string to an ArrayBuffer:
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
for (i = 0; i < byteString.length; i += 1) {
intArray[i] = byteString.charCodeAt(i);
}
// Separate out the mime component:
mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// Write the ArrayBuffer (or ArrayBufferView) to a blob:
if (hasBlobConstructor) {
return new Blob(
[hasArrayBufferViewSupport ? intArray : arrayBuffer],
{type: mimeString}
);
}
bb = new BlobBuilder();
bb.append(arrayBuffer);
return bb.getBlob(mimeString);
};
if (window.HTMLCanvasElement && !CanvasPrototype.toBlob) {
if (CanvasPrototype.mozGetAsFile) {
CanvasPrototype.toBlob = function (callback, type, quality) {
if (quality && CanvasPrototype.toDataURL && dataURLtoBlob) {
callback(dataURLtoBlob(this.toDataURL(type, quality)));
} else {
callback(this.mozGetAsFile('blob', type));
}
};
} else if (CanvasPrototype.toDataURL && dataURLtoBlob) {
CanvasPrototype.toBlob = function (callback, type, quality) {
callback(dataURLtoBlob(this.toDataURL(type, quality)));
};
}
}
window.dataURLtoBlob = dataURLtoBlob;
})(window);
/*jslint evil: true */
/*global window, URL, webkitURL, ActiveXObject */
(function (window, undef){
'use strict';
var
gid = 1,
noop = function (){},
document = window.document,
doctype = document.doctype || {},
userAgent = window.navigator.userAgent,
// https://github.com/blueimp/JavaScript-Load-Image/blob/master/load-image.js#L48
apiURL = (window.createObjectURL && window) || (window.URL && URL.revokeObjectURL && URL) || (window.webkitURL && webkitURL),
Blob = window.Blob,
File = window.File,
FileReader = window.FileReader,
FormData = window.FormData,
XMLHttpRequest = window.XMLHttpRequest,
jQuery = window.jQuery,
html5 = !!(File && (FileReader && (window.Uint8Array || FormData || XMLHttpRequest.prototype.sendAsBinary)))
&& !(/safari\//i.test(userAgent) && !/chrome\//i.test(userAgent) && /windows/i.test(userAgent)), // BugFix: https://github.com/mailru/FileAPI/issues/25
cors = html5 && ('withCredentials' in (new XMLHttpRequest)),
chunked = html5 && !!Blob && !!(Blob.prototype.webkitSlice || Blob.prototype.mozSlice || Blob.prototype.slice),
// https://github.com/blueimp/JavaScript-Canvas-to-Blob
dataURLtoBlob = window.dataURLtoBlob,
_rimg = /img/i,
_rcanvas = /canvas/i,
_rimgcanvas = /img|canvas/i,
_rinput = /input/i,
_rdata = /^data:[^,]+,/,
_toString = {}.toString,
Math = window.Math,
_SIZE_CONST = function (pow){
pow = new window.Number(Math.pow(1024, pow));
pow.from = function (sz){ return Math.round(sz * this); };
return pow;
},
_elEvents = {}, // element event listeners
_infoReader = [], // list of file info processors
_readerEvents = 'abort progress error load loadend',
_xhrPropsExport = 'status statusText readyState response responseXML responseText responseBody'.split(' '),
currentTarget = 'currentTarget', // for minimize
preventDefault = 'preventDefault', // and this too
_isArray = function (ar) {
return ar && ('length' in ar);
},
/**
* Iterate over a object or array
*/
_each = function (obj, fn, ctx){
if( obj ){
if( _isArray(obj) ){
for( var i = 0, n = obj.length; i < n; i++ ){
if( i in obj ){
fn.call(ctx, obj[i], i, obj);
}
}
}
else {
for( var key in obj ){
if( obj.hasOwnProperty(key) ){
fn.call(ctx, obj[key], key, obj);
}
}
}
}
},
/**
* Merge the contents of two or more objects together into the first object
*/
_extend = function (dst){
var args = arguments, i = 1, _ext = function (val, key){ dst[key] = val; };
for( ; i < args.length; i++ ){
_each(args[i], _ext);
}
return dst;
},
/**
* Add event listener
*/
_on = function (el, type, fn){
if( el ){
var uid = api.uid(el);
if( !_elEvents[uid] ){
_elEvents[uid] = {};
}
var isFileReader = (FileReader && el) && (el instanceof FileReader);
_each(type.split(/\s+/), function (type){
if( jQuery && !isFileReader){
jQuery.event.add(el, type, fn);
} else {
if( !_elEvents[uid][type] ){
_elEvents[uid][type] = [];
}
_elEvents[uid][type].push(fn);
if( el.addEventListener ){ el.addEventListener(type, fn, false); }
else if( el.attachEvent ){ el.attachEvent('on'+type, fn); }
else { el['on'+type] = fn; }
}
});
}
},
/**
* Remove event listener
*/
_off = function (el, type, fn){
if( el ){
var uid = api.uid(el), events = _elEvents[uid] || {};
var isFileReader = (FileReader && el) && (el instanceof FileReader);
_each(type.split(/\s+/), function (type){
if( jQuery && !isFileReader){
jQuery.event.remove(el, type, fn);
}
else {
var fns = events[type] || [], i = fns.length;
while( i-- ){
if( fns[i] === fn ){
fns.splice(i, 1);
break;
}
}
if( el.addEventListener ){ el.removeEventListener(type, fn, false); }
else if( el.detachEvent ){ el.detachEvent('on'+type, fn); }
else { el['on'+type] = null; }
}
});
}
},
_one = function(el, type, fn){
_on(el, type, function _(evt){
_off(el, type, _);
fn(evt);
});
},
_fixEvent = function (evt){
if( !evt.target ){ evt.target = window.event && window.event.srcElement || document; }
if( evt.target.nodeType === 3 ){ evt.target = evt.target.parentNode; }
return evt;
},
_supportInputAttr = function (attr){
var input = document.createElement('input');
input.setAttribute('type', "file");
return attr in input;
},
/**
* FileAPI (core object)
*/
api = {
version: '2.0.7',
cors: false,
html5: true,
media: false,
formData: true,
multiPassResize: true,
debug: false,
pingUrl: false,
multiFlash: false,
flashAbortTimeout: 0,
withCredentials: true,
staticPath: './dist/',
flashUrl: 0, // @default: './FileAPI.flash.swf'
flashImageUrl: 0, // @default: './FileAPI.flash.image.swf'
postNameConcat: function (name, idx){
return name + (idx != null ? '['+ idx +']' : '');
},
ext2mime: {
jpg: 'image/jpeg'
, tif: 'image/tiff'
, txt: 'text/plain'
},
// Fallback for flash
accept: {
'image/*': 'art bm bmp dwg dxf cbr cbz fif fpx gif ico iefs jfif jpe jpeg jpg jps jut mcf nap nif pbm pcx pgm pict pm png pnm qif qtif ras rast rf rp svf tga tif tiff xbm xbm xpm xwd'
, 'audio/*': 'm4a flac aac rm mpa wav wma ogg mp3 mp2 m3u mod amf dmf dsm far gdm imf it m15 med okt s3m stm sfx ult uni xm sid ac3 dts cue aif aiff wpl ape mac mpc mpp shn wv nsf spc gym adplug adx dsp adp ymf ast afc hps xs'
, 'video/*': 'm4v 3gp nsv ts ty strm rm rmvb m3u ifo mov qt divx xvid bivx vob nrg img iso pva wmv asf asx ogm m2v avi bin dat dvr-ms mpg mpeg mp4 mkv avc vp3 svq3 nuv viv dv fli flv wpl'
},
uploadRetry : 0,
networkDownRetryTimeout : 5000, // milliseconds, don't flood when network is down
chunkSize : 0,
chunkUploadRetry : 0,
chunkNetworkDownRetryTimeout : 2000, // milliseconds, don't flood when network is down
KB: _SIZE_CONST(1),
MB: _SIZE_CONST(2),
GB: _SIZE_CONST(3),
TB: _SIZE_CONST(4),
EMPTY_PNG: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=',
expando: 'fileapi' + (new Date).getTime(),
uid: function (obj){
return obj
? (obj[api.expando] = obj[api.expando] || api.uid())
: (++gid, api.expando + gid)
;
},
log: function (){
// ngf fix for IE8 #1071
if( api.debug && api._supportConsoleLog ){
if( api._supportConsoleLogApply ){
console.log.apply(console, arguments);
}
else {
console.log([].join.call(arguments, ' '));
}
}
},
/**
* Create new image
*
* @param {String} [src]
* @param {Function} [fn] 1. error -- boolean, 2. img -- Image element
* @returns {HTMLElement}
*/
newImage: function (src, fn){
var img = document.createElement('img');
if( fn ){
api.event.one(img, 'error load', function (evt){
fn(evt.type == 'error', img);
img = null;
});
}
img.src = src;
return img;
},
/**
* Get XHR
* @returns {XMLHttpRequest}
*/
getXHR: function (){
var xhr;
if( XMLHttpRequest ){
xhr = new XMLHttpRequest;
}
else if( window.ActiveXObject ){
try {
xhr = new ActiveXObject('MSXML2.XMLHttp.3.0');
} catch (e) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xhr;
},
isArray: _isArray,
support: {
dnd: cors && ('ondrop' in document.createElement('div')),
cors: cors,
html5: html5,
chunked: chunked,
dataURI: true,
accept: _supportInputAttr('accept'),
multiple: _supportInputAttr('multiple')
},
event: {
on: _on
, off: _off
, one: _one
, fix: _fixEvent
},
throttle: function(fn, delay) {
var id, args;
return function _throttle(){
args = arguments;
if( !id ){
fn.apply(window, args);
id = setTimeout(function (){
id = 0;
fn.apply(window, args);
}, delay);
}
};
},
F: function (){},
parseJSON: function (str){
var json;
if( window.JSON && JSON.parse ){
json = JSON.parse(str);
}
else {
json = (new Function('return ('+str.replace(/([\r\n])/g, '\\$1')+');'))();
}
return json;
},
trim: function (str){
str = String(str);
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
},
/**
* Simple Defer
* @return {Object}
*/
defer: function (){
var
list = []
, result
, error
, defer = {
resolve: function (err, res){
defer.resolve = noop;
error = err || false;
result = res;
while( res = list.shift() ){
res(error, result);
}
},
then: function (fn){
if( error !== undef ){
fn(error, result);
} else {
list.push(fn);
}
}
};
return defer;
},
queue: function (fn){
var
_idx = 0
, _length = 0
, _fail = false
, _end = false
, queue = {
inc: function (){
_length++;
},
next: function (){
_idx++;
setTimeout(queue.check, 0);
},
check: function (){
(_idx >= _length) && !_fail && queue.end();
},
isFail: function (){
return _fail;
},
fail: function (){
!_fail && fn(_fail = true);
},
end: function (){
if( !_end ){
_end = true;
fn();
}
}
}
;
return queue;
},
/**
* For each object
*
* @param {Object|Array} obj
* @param {Function} fn
* @param {*} [ctx]
*/
each: _each,
/**
* Async for
* @param {Array} array
* @param {Function} callback
*/
afor: function (array, callback){
var i = 0, n = array.length;
if( _isArray(array) && n-- ){
(function _next(){
callback(n != i && _next, array[i], i++);
})();
}
else {
callback(false);
}
},
/**
* Merge the contents of two or more objects together into the first object
*
* @param {Object} dst
* @return {Object}
*/
extend: _extend,
/**
* Is file?
* @param {File} file
* @return {Boolean}
*/
isFile: function (file){
return _toString.call(file) === '[object File]';
},
/**
* Is blob?
* @param {Blob} blob
* @returns {Boolean}
*/
isBlob: function (blob) {
return this.isFile(blob) || (_toString.call(blob) === '[object Blob]');
},
/**
* Is canvas element
*
* @param {HTMLElement} el
* @return {Boolean}
*/
isCanvas: function (el){
return el && _rcanvas.test(el.nodeName);
},
getFilesFilter: function (filter){
filter = typeof filter == 'string' ? filter : (filter.getAttribute && filter.getAttribute('accept') || '');
return filter ? new RegExp('('+ filter.replace(/\./g, '\\.').replace(/,/g, '|') +')$', 'i') : /./;
},
/**
* Read as DataURL
*
* @param {File|Element} file
* @param {Function} fn
*/
readAsDataURL: function (file, fn){
if( api.isCanvas(file) ){
_emit(file, fn, 'load', api.toDataURL(file));
}
else {
_readAs(file, fn, 'DataURL');
}
},
/**
* Read as Binary string
*
* @param {File} file
* @param {Function} fn
*/
readAsBinaryString: function (file, fn){
if( _hasSupportReadAs('BinaryString') ){
_readAs(file, fn, 'BinaryString');
} else {
// Hello IE10!
_readAs(file, function (evt){
if( evt.type == 'load' ){
try {
// dataURL -> binaryString
evt.result = api.toBinaryString(evt.result);
} catch (e){
evt.type = 'error';
evt.message = e.toString();
}
}
fn(evt);
}, 'DataURL');
}
},
/**
* Read as ArrayBuffer
*
* @param {File} file
* @param {Function} fn
*/
readAsArrayBuffer: function(file, fn){
_readAs(file, fn, 'ArrayBuffer');
},
/**
* Read as text
*
* @param {File} file
* @param {String} encoding
* @param {Function} [fn]
*/
readAsText: function(file, encoding, fn){
if( !fn ){
fn = encoding;
encoding = 'utf-8';
}
_readAs(file, fn, 'Text', encoding);
},
/**
* Convert image or canvas to DataURL
*
* @param {Element} el Image or Canvas element
* @param {String} [type] mime-type
* @return {String}
*/
toDataURL: function (el, type){
if( typeof el == 'string' ){
return el;
}
else if( el.toDataURL ){
return el.toDataURL(type || 'image/png');
}
},
/**
* Canvert string, image or canvas to binary string
*
* @param {String|Element} val
* @return {String}
*/
toBinaryString: function (val){
return window.atob(api.toDataURL(val).replace(_rdata, ''));
},
/**
* Read file or DataURL as ImageElement
*
* @param {File|String} file
* @param {Function} fn
* @param {Boolean} [progress]
*/
readAsImage: function (file, fn, progress){
if( api.isFile(file) ){
if( apiURL ){
/** @namespace apiURL.createObjectURL */
var data = apiURL.createObjectURL(file);
if( data === undef ){
_emit(file, fn, 'error');
}
else {
api.readAsImage(data, fn, progress);
}
}
else {
api.readAsDataURL(file, function (evt){
if( evt.type == 'load' ){
api.readAsImage(evt.result, fn, progress);
}
else if( progress || evt.type == 'error' ){
_emit(file, fn, evt, null, { loaded: evt.loaded, total: evt.total });
}
});
}
}
else if( api.isCanvas(file) ){
_emit(file, fn, 'load', file);
}
else if( _rimg.test(file.nodeName) ){
if( file.complete ){
_emit(file, fn, 'load', file);
}
else {
var events = 'error abort load';
_one(file, events, function _fn(evt){
if( evt.type == 'load' && apiURL ){
/** @namespace apiURL.revokeObjectURL */
apiURL.revokeObjectURL(file.src);
}
_off(file, events, _fn);
_emit(file, fn, evt, file);
});
}
}
else if( file.iframe ){
_emit(file, fn, { type: 'error' });
}
else {
// Created image
var img = api.newImage(file.dataURL || file);
api.readAsImage(img, fn, progress);
}
},
/**
* Make file by name
*
* @param {String} name
* @return {Array}
*/
checkFileObj: function (name){
var file = {}, accept = api.accept;
if( typeof name == 'object' ){
file = name;
}
else {
file.name = (name + '').split(/\\|\//g).pop();
}
if( file.type == null ){
file.type = file.name.split('.').pop();
}
_each(accept, function (ext, type){
ext = new RegExp(ext.replace(/\s/g, '|'), 'i');
if( ext.test(file.type) || api.ext2mime[file.type] ){
file.type = api.ext2mime[file.type] || (type.split('/')[0] +'/'+ file.type);
}
});
return file;
},
/**
* Get drop files
*
* @param {Event} evt
* @param {Function} callback
*/
getDropFiles: function (evt, callback){
var
files = []
, dataTransfer = _getDataTransfer(evt)
, entrySupport = _isArray(dataTransfer.items) && dataTransfer.items[0] && _getAsEntry(dataTransfer.items[0])
, queue = api.queue(function (){ callback(files); })
;
_each((entrySupport ? dataTransfer.items : dataTransfer.files) || [], function (item){
queue.inc();
try {
if( entrySupport ){
_readEntryAsFiles(item, function (err, entryFiles){
if( err ){
api.log('[err] getDropFiles:', err);
} else {
files.push.apply(files, entryFiles);
}
queue.next();
});
}
else {
_isRegularFile(item, function (yes){
yes && files.push(item);
queue.next();
});
}
}
catch( err ){
queue.next();
api.log('[err] getDropFiles: ', err);
}
});
queue.check();
},
/**
* Get file list
*
* @param {HTMLInputElement|Event} input
* @param {String|Function} [filter]
* @param {Function} [callback]
* @return {Array|Null}
*/
getFiles: function (input, filter, callback){
var files = [];
if( callback ){
api.filterFiles(api.getFiles(input), filter, callback);
return null;
}
if( input.jquery ){
// jQuery object
input.each(function (){
files = files.concat(api.getFiles(this));
});
input = files;
files = [];
}
if( typeof filter == 'string' ){
filter = api.getFilesFilter(filter);
}
if( input.originalEvent ){
// jQuery event
input = _fixEvent(input.originalEvent);
}
else if( input.srcElement ){
// IE Event
input = _fixEvent(input);
}
if( input.dataTransfer ){
// Drag'n'Drop
input = input.dataTransfer;
}
else if( input.target ){
// Event
input = input.target;
}
if( input.files ){
// Input[type="file"]
files = input.files;
if( !html5 ){
// Partial support for file api
files[0].blob = input;
files[0].iframe = true;
}
}
else if( !html5 && isInputFile(input) ){
if( api.trim(input.value) ){
files = [api.checkFileObj(input.value)];
files[0].blob = input;
files[0].iframe = true;
}
}
else if( _isArray(input) ){
files = input;
}
return api.filter(files, function (file){ return !filter || filter.test(file.name); });
},
/**
* Get total file size
* @param {Array} files
* @return {Number}
*/
getTotalSize: function (files){
var size = 0, i = files && files.length;
while( i-- ){
size += files[i].size;
}
return size;
},
/**
* Get image information
*
* @param {File} file
* @param {Function} fn
*/
getInfo: function (file, fn){
var info = {}, readers = _infoReader.concat();
if( api.isFile(file) ){
(function _next(){
var reader = readers.shift();
if( reader ){
if( reader.test(file.type) ){
reader(file, function (err, res){
if( err ){
fn(err);
}
else {
_extend(info, res);
_next();
}
});
}
else {
_next();
}
}
else {
fn(false, info);
}
})();
}
else {
fn('not_support_info', info);
}
},
/**
* Add information reader
*
* @param {RegExp} mime
* @param {Function} fn
*/
addInfoReader: function (mime, fn){
fn.test = function (type){ return mime.test(type); };
_infoReader.push(fn);
},
/**
* Filter of array
*
* @param {Array} input
* @param {Function} fn
* @return {Array}
*/
filter: function (input, fn){
var result = [], i = 0, n = input.length, val;
for( ; i < n; i++ ){
if( i in input ){
val = input[i];
if( fn.call(val, val, i, input) ){
result.push(val);
}
}
}
return result;
},
/**
* Filter files
*
* @param {Array} files
* @param {Function} eachFn
* @param {Function} resultFn