forked from FineUploader/fine-uploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileuploader.js
executable file
·1633 lines (1423 loc) · 51.7 KB
/
fileuploader.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
/**
* http://github.com/Valums-File-Uploader/file-uploader
*
* Multiple file upload component with progress-bar, drag-and-drop.
*
* Have ideas for improving this JS for the general community?
* Submit your changes at: https://github.com/Valums-File-Uploader/file-uploader
* Readme at https://github.com/valums/file-uploader/blob/2.0/readme.md
*
* VERSION 2.1-SNAPSHOT
* Original version: 1.0 © 2010 Andrew Valums ( andrew(at)valums.com )
* Current Maintainer (2.0+): © 2012, Ray Nicholus ( fineuploader(at)garstasio.com )
*
* Licensed under MIT license, GNU GPL 2 or later, GNU LGPL 2 or later, see license.txt.
*/
//
// Helper functions
//
var qq = qq || {};
/**
* Adds all missing properties from second obj to first obj
*/
qq.extend = function(first, second){
for (var prop in second){
first[prop] = second[prop];
}
};
/**
* Searches for a given element in the array, returns -1 if it is not present.
* @param {Number} [from] The index at which to begin the search
*/
qq.indexOf = function(arr, elt, from){
if (arr.indexOf) return arr.indexOf(elt, from);
from = from || 0;
var len = arr.length;
if (from < 0) from += len;
for (; from < len; from++){
if (from in arr && arr[from] === elt){
return from;
}
}
return -1;
};
qq.getUniqueId = (function(){
var id = 0;
return function(){ return id++; };
})();
//
// Browsers and platforms detection
qq.ie = function(){ return navigator.userAgent.indexOf('MSIE') != -1; }
qq.safari = function(){ return navigator.vendor != undefined && navigator.vendor.indexOf("Apple") != -1; }
qq.chrome = function(){ return navigator.vendor != undefined && navigator.vendor.indexOf('Google') != -1; }
qq.firefox = function(){ return (navigator.userAgent.indexOf('Mozilla') != -1 && navigator.vendor != undefined && navigator.vendor == ''); }
qq.windows = function(){ return navigator.platform == "Win32"; }
//
// Events
/** Returns the function which detaches attached event */
qq.attach = function(element, type, fn){
if (element.addEventListener){
element.addEventListener(type, fn, false);
} else if (element.attachEvent){
element.attachEvent('on' + type, fn);
}
return function() {
qq.detach(element, type, fn)
}
};
qq.detach = function(element, type, fn){
if (element.removeEventListener){
element.removeEventListener(type, fn, false);
} else if (element.attachEvent){
element.detachEvent('on' + type, fn);
}
};
qq.preventDefault = function(e){
if (e.preventDefault){
e.preventDefault();
} else{
e.returnValue = false;
}
};
//
// Node manipulations
/**
* Insert node a before node b.
*/
qq.insertBefore = function(a, b){
b.parentNode.insertBefore(a, b);
};
qq.remove = function(element){
element.parentNode.removeChild(element);
};
qq.contains = function(parent, descendant){
// compareposition returns false in this case
if (parent == descendant) return true;
if (parent.contains){
return parent.contains(descendant);
} else {
return !!(descendant.compareDocumentPosition(parent) & 8);
}
};
/**
* Creates and returns element from html string
* Uses innerHTML to create an element
*/
qq.toElement = (function(){
var div = document.createElement('div');
return function(html){
div.innerHTML = html;
var element = div.firstChild;
div.removeChild(element);
return element;
};
})();
//
// Node properties and attributes
/**
* Sets styles for an element.
* Fixes opacity in IE6-8.
*/
qq.css = function(element, styles){
if (styles.opacity != null){
if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
}
}
qq.extend(element.style, styles);
};
qq.hasClass = function(element, name){
var re = new RegExp('(^| )' + name + '( |$)');
return re.test(element.className);
};
qq.addClass = function(element, name){
if (!qq.hasClass(element, name)){
element.className += ' ' + name;
}
};
qq.removeClass = function(element, name){
var re = new RegExp('(^| )' + name + '( |$)');
element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
};
qq.setText = function(element, text){
element.innerText = text;
element.textContent = text;
};
//
// Selecting elements
qq.children = function(element){
var children = [],
child = element.firstChild;
while (child){
if (child.nodeType == 1){
children.push(child);
}
child = child.nextSibling;
}
return children;
};
qq.getByClass = function(element, className){
if (element.querySelectorAll){
return element.querySelectorAll('.' + className);
}
var result = [];
var candidates = element.getElementsByTagName("*");
var len = candidates.length;
for (var i = 0; i < len; i++){
if (qq.hasClass(candidates[i], className)){
result.push(candidates[i]);
}
}
return result;
};
/**
* obj2url() takes a json-object as argument and generates
* a querystring. pretty much like jQuery.param()
*
* how to use:
*
* `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
*
* will result in:
*
* `http://any.url/upload?otherParam=value&a=b&c=d`
*
* @param Object JSON-Object
* @param String current querystring-part
* @return String encoded querystring
*/
qq.obj2url = function(obj, temp, prefixDone){
var uristrings = [],
prefix = '&',
add = function(nextObj, i){
var nextTemp = temp
? (/\[\]$/.test(temp)) // prevent double-encoding
? temp
: temp+'['+i+']'
: i;
if ((nextTemp != 'undefined') && (i != 'undefined')) {
uristrings.push(
(typeof nextObj === 'object')
? qq.obj2url(nextObj, nextTemp, true)
: (Object.prototype.toString.call(nextObj) === '[object Function]')
? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
: encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
);
}
};
if (!prefixDone && temp) {
prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
uristrings.push(temp);
uristrings.push(qq.obj2url(obj));
} else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
// we wont use a for-in-loop on an array (performance)
for (var i = 0, len = obj.length; i < len; ++i){
add(obj[i], i);
}
} else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){
// for anything else but a scalar, we will use for-in-loop
for (var i in obj){
add(obj[i], i);
}
} else {
uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
}
return uristrings.join(prefix)
.replace(/^&/, '')
.replace(/%20/g, '+');
};
//
//
// Uploader Classes
//
//
var qq = qq || {};
/**
* Creates upload button, validates upload, but doesn't create file list or dd.
*/
qq.FileUploaderBasic = function(o){
var that = this;
this._options = {
// set to true to see the server response
debug: false,
action: '/server/upload',
params: {},
customHeaders: {},
button: null,
multiple: true,
maxConnections: 3,
disableCancelForFormUploads: false,
autoUpload: true,
forceMultipart: false,
// validation
allowedExtensions: [],
acceptFiles: null, // comma separated string of mime-types for browser to display in browse dialog
sizeLimit: 0,
minSizeLimit: 0,
stopOnFirstInvalidFile: true,
// events
// return false to cancel submit
onSubmit: function(id, fileName){},
onComplete: function(id, fileName, responseJSON){},
onCancel: function(id, fileName){},
onUpload: function(id, fileName, xhr){},
onProgress: function(id, fileName, loaded, total){},
onError: function(id, fileName, reason) {},
// messages
messages: {
typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
noFilesError: "No files to upload.",
onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
},
showMessage: function(message){
alert(message);
},
inputName: 'qqfile'
};
qq.extend(this._options, o);
this._wrapCallbacks();
qq.extend(this, qq.DisposeSupport);
// number of files being uploaded
this._filesInProgress = 0;
this._storedFileIds = [];
this._handler = this._createUploadHandler();
if (this._options.button){
this._button = this._createUploadButton(this._options.button);
}
this._preventLeaveInProgress();
};
qq.FileUploaderBasic.prototype = {
log: function(str){
if (this._options.debug && window.console) console.log('[uploader] ' + str);
},
setParams: function(params){
this._options.params = params;
},
getInProgress: function(){
return this._filesInProgress;
},
uploadStoredFiles: function(){
while(this._storedFileIds.length) {
this._filesInProgress++;
this._handler.upload(this._storedFileIds.shift(), this._options.params);
}
},
clearStoredFiles: function(){
this._storedFileIds = [];
},
_createUploadButton: function(element){
var self = this;
var button = new qq.UploadButton({
element: element,
multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
acceptFiles: this._options.acceptFiles,
onChange: function(input){
self._onInputChange(input);
}
});
this.addDisposer(function() { button.dispose(); });
return button;
},
_createUploadHandler: function(){
var self = this,
handlerClass;
if(qq.UploadHandlerXhr.isSupported()){
handlerClass = 'UploadHandlerXhr';
} else {
handlerClass = 'UploadHandlerForm';
}
var handler = new qq[handlerClass]({
debug: this._options.debug,
action: this._options.action,
forceMultipart: this._options.forceMultipart,
maxConnections: this._options.maxConnections,
customHeaders: this._options.customHeaders,
inputName: this._options.inputName,
demoMode: this._options.demoMode,
onProgress: function(id, fileName, loaded, total){
self._onProgress(id, fileName, loaded, total);
self._options.onProgress(id, fileName, loaded, total);
},
onComplete: function(id, fileName, result){
self._onComplete(id, fileName, result);
self._options.onComplete(id, fileName, result);
},
onCancel: function(id, fileName){
self._onCancel(id, fileName);
self._options.onCancel(id, fileName);
},
onError: self._options.onError,
onUpload: function(id, fileName, xhr){
self._onUpload(id, fileName, xhr);
self._options.onUpload(id, fileName, xhr);
}
});
return handler;
},
_preventLeaveInProgress: function(){
var self = this;
this._attach(window, 'beforeunload', function(e){
if (!self._filesInProgress){return;}
var e = e || window.event;
// for ie, ff
e.returnValue = self._options.messages.onLeave;
// for webkit
return self._options.messages.onLeave;
});
},
_onSubmit: function(id, fileName){
if (this._options.autoUpload) {
this._filesInProgress++;
}
},
_onProgress: function(id, fileName, loaded, total){
},
_onComplete: function(id, fileName, result){
this._filesInProgress--;
if (!result.success){
var errorReason = result.error ? result.error : "Upload failure reason unknown";
this._options.onError(id, fileName, errorReason);
}
},
_onCancel: function(id, fileName){
var storedFileIndex = qq.indexOf(this._storedFileIds, id);
if (this._options.autoUpload || storedFileIndex < 0) {
this._filesInProgress--;
}
else if (!this._options.autoUpload) {
this._storedFileIds.splice(storedFileIndex, 1);
}
},
_onUpload: function(id, fileName, xhr){
},
_onInputChange: function(input){
if (this._handler instanceof qq.UploadHandlerXhr){
this._uploadFileList(input.files);
} else {
if (this._validateFile(input)){
this._uploadFile(input);
}
}
this._button.reset();
},
_uploadFileList: function(files){
if (files.length > 0) {
for (var i=0; i<files.length; i++){
if (this._validateFile(files[i])){
this._uploadFile(files[i]);
} else {
if (this._options.stopOnFirstInvalidFile){
return;
}
}
}
}
else {
this._error('noFilesError', "");
}
},
_uploadFile: function(fileContainer){
var id = this._handler.add(fileContainer);
var fileName = this._handler.getName(id);
if (this._options.onSubmit(id, fileName) !== false){
this._onSubmit(id, fileName);
if (this._options.autoUpload) {
this._handler.upload(id, this._options.params);
}
else {
this._storeFileForLater(id);
}
}
},
_storeFileForLater: function(id) {
this._storedFileIds.push(id);
},
_validateFile: function(file){
var name, size;
if (file.value){
// it is a file input
// get input value and remove path to normalize
name = file.value.replace(/.*(\/|\\)/, "");
} else {
// fix missing properties in Safari 4 and firefox 11.0a2
name = (file.fileName !== null && file.fileName !== undefined) ? file.fileName : file.name;
size = (file.fileSize !== null && file.fileSize !== undefined) ? file.fileSize : file.size;
}
if (! this._isAllowedExtension(name)){
this._error('typeError', name);
return false;
} else if (size === 0){
this._error('emptyError', name);
return false;
} else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
this._error('sizeError', name);
return false;
} else if (size && size < this._options.minSizeLimit){
this._error('minSizeError', name);
return false;
}
return true;
},
_error: function(code, fileName){
var message = this._options.messages[code];
function r(name, replacement){ message = message.replace(name, replacement); }
var extensions = this._options.allowedExtensions.join(', ');
r('{file}', this._formatFileName(fileName));
r('{extensions}', extensions);
r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
this._options.onError(null, fileName, message);
this._options.showMessage(message);
},
_formatFileName: function(name){
if (name.length > 33){
name = name.slice(0, 19) + '...' + name.slice(-13);
}
return name;
},
_isAllowedExtension: function(fileName){
var ext = (-1 !== fileName.indexOf('.'))
? fileName.replace(/.*[.]/, '').toLowerCase()
: '';
var allowed = this._options.allowedExtensions;
if (!allowed.length){return true;}
for (var i=0; i<allowed.length; i++){
if (allowed[i].toLowerCase() == ext){ return true;}
}
return false;
},
_formatSize: function(bytes){
var i = -1;
do {
bytes = bytes / 1024;
i++;
} while (bytes > 99);
return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
},
_wrapCallbacks: function() {
var self, safeCallback;
self = this;
safeCallback = function(callback, args) {
try {
return callback.apply(this, args);
}
catch (exception) {
self.log("Caught " + exception + " in callback: " + callback);
}
}
for (var prop in this._options) {
if (/^on[A-Z]/.test(prop)) {
(function() {
var oldCallback = self._options[prop];
self._options[prop] = function() {
return safeCallback(oldCallback, arguments);
}
}());
}
}
}
};
/**
* Class that creates upload widget with drag-and-drop and file list
* @inherits qq.FileUploaderBasic
*/
qq.FileUploader = function(o){
// call parent constructor
qq.FileUploaderBasic.apply(this, arguments);
// additional options
qq.extend(this._options, {
element: null,
// if set, will be used instead of qq-upload-list in template
listElement: null,
dragText: 'Drop files here to upload',
extraDropzones : [],
hideDropzones : true,
disableDefaultDropzone: false,
uploadButtonText: 'Upload a file',
cancelButtonText: 'Cancel',
failUploadText: 'Upload failed',
template: '<div class="qq-uploader">' +
(!this._options.disableDefaultDropzone ? '<div class="qq-upload-drop-area"><span>{dragText}</span></div>' : '') +
(!this._options.button ? '<div class="qq-upload-button">{uploadButtonText}</div>' : '') +
(!this._options.listElement ? '<ul class="qq-upload-list"></ul>' : '') +
'</div>',
// template for one item in file list
fileTemplate: '<li>' +
'<div class="qq-progress-bar"></div>' +
'<span class="qq-upload-spinner"></span>' +
'<span class="qq-upload-finished"></span>' +
'<span class="qq-upload-file"></span>' +
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
'<span class="qq-upload-failed-text">{failUploadtext}</span>' +
'</li>',
classes: {
// used to get elements from templates
button: 'qq-upload-button',
drop: 'qq-upload-drop-area',
dropActive: 'qq-upload-drop-area-active',
dropDisabled: 'qq-upload-drop-area-disabled',
list: 'qq-upload-list',
progressBar: 'qq-progress-bar',
file: 'qq-upload-file',
spinner: 'qq-upload-spinner',
finished: 'qq-upload-finished',
size: 'qq-upload-size',
cancel: 'qq-upload-cancel',
failText: 'qq-upload-failed-text',
// added to list item <li> when upload completes
// used in css to hide progress spinner
success: 'qq-upload-success',
fail: 'qq-upload-fail',
successIcon: null,
failIcon: null
},
extraMessages: {
formatProgress: "{percent}% of {total_size}",
tooManyFilesError: "You may only drop one file"
},
failedUploadTextDisplay: {
mode: 'default', //default, custom, or none
maxChars: 50,
responseProperty: 'error',
enableTooltip: true
}
});
// overwrite options with user supplied
qq.extend(this._options, o);
this._wrapCallbacks();
qq.extend(this._options.messages, this._options.extraMessages);
// overwrite the upload button text if any
// same for the Cancel button and Fail message text
this._options.template = this._options.template.replace(/\{dragText\}/g, this._options.dragText);
this._options.template = this._options.template.replace(/\{uploadButtonText\}/g, this._options.uploadButtonText);
this._options.fileTemplate = this._options.fileTemplate.replace(/\{cancelButtonText\}/g, this._options.cancelButtonText);
this._options.fileTemplate = this._options.fileTemplate.replace(/\{failUploadtext\}/g, this._options.failUploadText);
this._element = this._options.element;
this._element.innerHTML = this._options.template;
this._listElement = this._options.listElement || this._find(this._element, 'list');
this._classes = this._options.classes;
if (!this._button) {
this._button = this._createUploadButton(this._find(this._element, 'button'));
}
this._bindCancelEvent();
this._setupDragDrop();
};
// inherit from Basic Uploader
qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);
qq.extend(qq.FileUploader.prototype, {
clearStoredFiles: function() {
qq.FileUploaderBasic.prototype.clearStoredFiles.apply(this, arguments);
this._listElement.innerHTML = "";
},
addExtraDropzone: function(element){
this._setupExtraDropzone(element);
},
removeExtraDropzone: function(element){
var dzs = this._options.extraDropzones;
for(var i in dzs) if (dzs[i] === element) return this._options.extraDropzones.splice(i,1);
},
_leaving_document_out: function(e){
return ((qq.chrome() || (qq.safari() && qq.windows())) && e.clientX == 0 && e.clientY == 0) // null coords for Chrome and Safari Windows
|| (qq.firefox() && !e.relatedTarget); // null e.relatedTarget for Firefox
},
_storeFileForLater: function(id) {
qq.FileUploaderBasic.prototype._storeFileForLater.apply(this, arguments);
var item = this._getItemByFileId(id);
this._find(item, 'spinner').style.display = "none";
},
/**
* Gets one of the elements listed in this._options.classes
**/
_find: function(parent, type){
var element = qq.getByClass(parent, this._options.classes[type])[0];
if (!element){
throw new Error('element not found ' + type);
}
return element;
},
_setupExtraDropzone: function(element){
this._options.extraDropzones.push(element);
this._setupDropzone(element);
},
_setupDropzone: function(dropArea){
var self = this;
var dz = new qq.UploadDropZone({
element: dropArea,
onEnter: function(e){
qq.addClass(dropArea, self._classes.dropActive);
e.stopPropagation();
},
onLeave: function(e){
//e.stopPropagation();
},
onLeaveNotDescendants: function(e){
qq.removeClass(dropArea, self._classes.dropActive);
},
onDrop: function(e){
if (self._options.hideDropzones) {
dropArea.style.display = 'none';
}
qq.removeClass(dropArea, self._classes.dropActive);
if (e.dataTransfer.files.length > 1 && !self._options.multiple) {
self._error('tooManyFilesError', "");
}
else {
self._uploadFileList(e.dataTransfer.files);
}
}
});
this.addDisposer(function() { dz.dispose(); });
if (this._options.hideDropzones) {
dropArea.style.display = 'none';
}
},
_setupDragDrop: function(){
var self = this;
if (!this._options.disableDefaultDropzone) {
var dropArea = this._find(this._element, 'drop');
this._options.extraDropzones.push(dropArea);
}
var dropzones = this._options.extraDropzones;
var i;
for (i=0; i < dropzones.length; i++){
this._setupDropzone(dropzones[i]);
}
// IE <= 9 does not support the File API used for drag+drop uploads
// Any volunteers to enable & test this for IE10?
if (!this._options.disableDefaultDropzone && !qq.ie()) {
this._attach(document, 'dragenter', function(e){
if (qq.hasClass(dropArea, self._classes.dropDisabled)) return;
dropArea.style.display = 'block';
for (i=0; i < dropzones.length; i++){ dropzones[i].style.display = 'block'; }
});
}
this._attach(document, 'dragleave', function(e){
// only fire when leaving document out
if (self._options.hideDropzones && qq.FileUploader.prototype._leaving_document_out(e)) {
for (i=0; i < dropzones.length; i++) {
dropzones[i].style.display = 'none';
}
}
});
qq.attach(document, 'drop', function(e){
if (self._options.hideDropzones) {
for (i=0; i < dropzones.length; i++){
dropzones[i].style.display = 'none';
}
}
e.preventDefault();
});
},
_onSubmit: function(id, fileName){
qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
this._addToList(id, fileName);
},
// Update the progress bar & percentage as the file is uploaded
_onProgress: function(id, fileName, loaded, total){
qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);
var item = this._getItemByFileId(id);
if (loaded === total) {
var cancelLink = this._find(item, 'cancel');
cancelLink.style.display = 'none';
}
var size = this._find(item, 'size');
size.style.display = 'inline';
var text;
var percent = Math.round(loaded / total * 100);
if (loaded != total) {
// If still uploading, display percentage
text = this._formatProgress(loaded, total);
} else {
// If complete, just display final size
text = this._formatSize(total);
}
// Update progress bar <span> tag
this._find(item, 'progressBar').style.width = percent + '%';
qq.setText(size, text);
},
_onComplete: function(id, fileName, result){
qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);
var item = this._getItemByFileId(id);
qq.remove(this._find(item, 'progressBar'));
if (!this._options.disableCancelForFormUploads || qq.UploadHandlerXhr.isSupported()) {
qq.remove(this._find(item, 'cancel'));
}
qq.remove(this._find(item, 'spinner'));
if (result.success){
qq.addClass(item, this._classes.success);
if (this._classes.successIcon) {
this._find(item, 'finished').style.display = "inline-block";
qq.addClass(item, this._classes.successIcon)
}
} else {
qq.addClass(item, this._classes.fail);
if (this._classes.failIcon) {
this._find(item, 'finished').style.display = "inline-block";
qq.addClass(item, this._classes.failIcon)
}
this._controlFailureTextDisplay(item, result);
}
},
_onUpload: function(id, fileName, xhr){
qq.FileUploaderBasic.prototype._onUpload.apply(this, arguments);
var item = this._getItemByFileId(id);
if (qq.UploadHandlerXhr.isSupported()) {
this._find(item, 'progressBar').style.display = "block";
}
var spinnerEl = this._find(item, 'spinner');
if (spinnerEl.style.display == "none") {
spinnerEl.style.display = "inline-block";
}
},
_addToList: function(id, fileName){
var item = qq.toElement(this._options.fileTemplate);
if (this._options.disableCancelForFormUploads && !qq.UploadHandlerXhr.isSupported()) {
var cancelLink = this._find(item, 'cancel');
qq.remove(cancelLink);
}
item.qqFileId = id;
var fileElement = this._find(item, 'file');
qq.setText(fileElement, this._formatFileName(fileName));
this._find(item, 'size').style.display = 'none';
if (!this._options.multiple) this._clearList();
this._listElement.appendChild(item);
},
_clearList: function(){
this._listElement.innerHTML = '';
this.clearStoredFiles();
},
_getItemByFileId: function(id){
var item = this._listElement.firstChild;
// there can't be txt nodes in dynamically created list
// and we can use nextSibling
while (item){
if (item.qqFileId == id) return item;
item = item.nextSibling;
}
},
/**
* delegate click event for cancel link
**/
_bindCancelEvent: function(){
var self = this,
list = this._listElement;
this._attach(list, 'click', function(e){
e = e || window.event;
var target = e.target || e.srcElement;
if (qq.hasClass(target, self._classes.cancel)){
qq.preventDefault(e);
var item = target.parentNode;
self._handler.cancel(item.qqFileId);
qq.remove(item);
}
});
},
_formatProgress: function (uploadedSize, totalSize) {
var message = this._options.messages.formatProgress;
function r(name, replacement) { message = message.replace(name, replacement); }
r('{percent}', Math.round(uploadedSize / totalSize * 100));
r('{total_size}', this._formatSize(totalSize));
return message;
},
_controlFailureTextDisplay: function(item, response) {
var mode, maxChars, responseProperty, failureReason, shortFailureReason;
mode = this._options.failedUploadTextDisplay.mode;
maxChars = this._options.failedUploadTextDisplay.maxChars;
responseProperty = this._options.failedUploadTextDisplay.responseProperty;
if (mode === 'custom') {
var failureReason = response[responseProperty];
if (failureReason) {
if (failureReason.length > maxChars) {
shortFailureReason = failureReason.substring(0, maxChars) + '...';
}
this._find(item, 'failText').innerText = shortFailureReason || failureReason;
if (this._options.failedUploadTextDisplay.enableTooltip) {
this._showTooltip(item, failureReason);
}
}
else {
this.log("'" + responseProperty + "' is not a valid property on the server response.");
}
}
else if (mode === 'none') {
qq.remove(this._find(item, 'failText'));
}
else if (mode !== 'default') {
this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid");
}
},
//TODO turn this into a real tooltip, with click trigger (so it is usable on mobile devices). See case #355 for details.
_showTooltip: function(item, text) {
item.title = text;
}
});
qq.UploadDropZone = function(o){
this._options = {
element: null,
onEnter: function(e){},
onLeave: function(e){},
// is not fired when leaving element by hovering descendants
onLeaveNotDescendants: function(e){},
onDrop: function(e){}
};
qq.extend(this._options, o);
qq.extend(this, qq.DisposeSupport);
this._element = this._options.element;
this._disableDropOutside();
this._attachEvents();
};
qq.UploadDropZone.prototype = {
_dragover_should_be_canceled: function(){
return qq.safari() || (qq.firefox() && qq.windows());
},
_disableDropOutside: function(e){
// run only once for all instances
if (!qq.UploadDropZone.dropOutsideDisabled ){
// for these cases we need to catch onDrop to reset dropArea
if (this._dragover_should_be_canceled){
qq.attach(document, 'dragover', function(e){