forked from LPology/Simple-Ajax-Uploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleAjaxUploader.js
1284 lines (1117 loc) · 33.7 KB
/
SimpleAjaxUploader.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
/**
* Simple Ajax Uploader
* Version 1.6.4
* https://github.com/LPology/Simple-Ajax-Uploader
*
* Copyright 2012-2013 LPology, LLC
* Released under the MIT license
*/
;(function(window, document, undefined) {
"use strict";
var ss = window.ss || {};
/**
* Converts object to query string
*/
ss.obj2string = function(obj, prefix) {
var str = [];
if (typeof obj !== 'object') {
return '';
}
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var k = prefix ? prefix + "[" + prop + "]" : prop, v = obj[prop];
str.push(typeof v === 'object' ?
ss.obj2string(v, k) :
encodeURIComponent(k) + '=' + encodeURIComponent(v));
}
}
return str.join('&');
};
/**
* Copies all missing properties from second object to first object
*/
ss.extendObj = function(first, second) {
if (typeof first !== 'object' || typeof second !== 'object') {
return false;
}
for (var prop in second) {
if (second.hasOwnProperty(prop)) {
first[prop] = second[prop];
}
}
};
/**
* Returns true if item is found in array
*/
ss.contains = function(array, item) {
var i = array.length;
while (i--) {
if (array[i] === item) {
return true;
}
}
return false;
};
/**
* Remove all instances of an item from an array
*/
ss.removeItem = function(array, item) {
var i = array.length;
while (i--) {
if (array[i] == item) {
array.splice(i, 1);
}
}
};
ss.addEvent = function(elem, type, fn) {
if (typeof elem === 'string') {
elem = document.getElementById(elem);
}
if (elem.attachEvent) {
elem.attachEvent('on'+type, fn);
} else {
elem.addEventListener(type, fn, false);
}
};
ss.removeEvent = function(elem, type, fn) {
if (typeof elem === 'string') {
elem = document.getElementById(elem);
}
if (elem.attachEvent) {
elem.detachEvent('on' + type, fn);
} else {
elem.removeEventListener(type, fn, false);
}
};
ss.newXHR = function() {
if (typeof(XMLHttpRequest) !== undefined) {
return new window.XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new window.ActiveXObject('Microsoft.XMLHTTP');
} catch (err) {
return false;
}
}
};
/**
* Parses a JSON string and returns a Javascript object
* Parts borrowed from www.jquery.com
*/
ss.parseJSON = function(data) {
if (!data || typeof data !== 'string') {
return false;
}
data = ss.trim(data);
if (window.JSON && window.JSON.parse) {
try {
return window.JSON.parse(data);
} catch (err) {
return false;
}
}
if (data) {
if (/^[\],:{}\s]*$/.test( data.replace(/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, "@" )
.replace(/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, "]" )
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
return ( new Function( "return " + data ) )();
}
}
return false;
};
/**
* Calculates offsetTop/offsetLeft coordinates of parent
* element if getBoundingClientRect is not supported
*/
ss.getOffsetSum = function(elem) {
var top = 0,
left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return {top: top, left: left};
};
/**
* Calculates offsetTop/offsetLeft coordinates of parent
* element with getBoundingClientRect
*/
ss.getOffsetRect = function(elem) {
var box = elem.getBoundingClientRect(),
body = document.body,
docElem = document.documentElement,
scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop,
scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
};
/**
* Get offset with best available method
* Not sure where I came across this function. Thanks to whoever wrote it, though.
*/
ss.getOffset = function(elem) {
if (elem.getBoundingClientRect) {
return ss.getOffsetRect(elem);
} else {
return ss.getOffsetSum(elem);
}
};
/**
* Returns left, top, right and bottom properties describing the border-box,
* in pixels, with the top-left relative to the body
*/
ss.getBox = function(el) {
var left,
right,
top,
bottom,
offset = ss.getOffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetWidth;
bottom = top + el.offsetHeight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
};
/**
* Helper that takes object literal
* and add all properties to element.style
* @param {Element} el
* @param {Object} styles
*/
ss.addStyles = function(el, styles) {
for (var name in styles) {
if (styles.hasOwnProperty(name)) {
el.style[name] = styles[name];
}
}
};
/**
* Function places an absolutely positioned
* element on top of the specified element
* copying position and dimensions.
*/
ss.copyLayout = function(from, to) {
var box = ss.getBox(from);
ss.addStyles(to, {
position: 'absolute',
left : box.left + 'px',
top : box.top + 'px',
width : from.offsetWidth + 'px',
height : from.offsetHeight + 'px'
});
};
/**
* Creates and returns element from html chunk
*/
ss.toElement = (function() {
var div = document.createElement('div');
return function(html){
div.innerHTML = html;
var element = div.firstChild;
div.removeChild(element);
return element;
};
})();
/**
* Generates unique id
*/
ss.getUID = (function() {
var id = 0;
return function(){
return id++;
};
})();
/**
* Removes white space from left and right of string
*/
ss.trim = function(text) {
return text.toString().replace(/^\s+/, '').replace( /\s+$/, '');
};
/**
* Extract file name from path
*/
ss.getFilename = function(path) {
return path.replace(/.*(\/|\\)/, '');
};
/**
* Get file extension
*/
ss.getExt = function(file) {
return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
};
/**
* Check whether element has a particular CSS class
*/
ss.hasClass = function(element, name) {
var re = new RegExp('(^| )' + name + '( |$)');
return re.test(element.className);
};
/**
* Adds CSS class to an element
*/
ss.addClass = function(element, name) {
if (!name || name === '') {
return false;
}
if (!ss.hasClass(element, name)) {
element.className += ' ' + name;
}
};
/**
* Removes CSS class from an element
*/
ss.removeClass = function(element, name) {
var re = new RegExp('(^| )' + name + '( |$)');
element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, '');
};
/**
* Removes element from the DOM
*/
ss.remove = function(elem) {
if (elem.parentNode) {
elem.parentNode.removeChild(elem);
}
};
/**
* Accepts either a jQuery object, a string containing an element ID, or an element,
* verifies that it exists, and returns the element.
* @param {Mixed} elem
* @return {Element}
*/
ss.verifyElem = function(elem) {
if (typeof jQuery !== 'undefined' && elem instanceof jQuery) {
elem = elem[0];
} else if (typeof elem === 'string') {
if (/^#.*/.test(elem)) {
elem = elem.slice(1);
}
elem = document.getElementById(elem);
}
if (!elem || elem.nodeType !== 1) {
return false;
}
if (elem.nodeName.toUpperCase() == 'A') {
ss.addEvent(elem, 'click', function(e) {
if (e && e.preventDefault) {
e.preventDefault();
} else if (window.event) {
window.event.returnValue = false;
}
});
}
return elem;
};
/**
* @constructor
* @param {Object} options
View README.md for documentation
*/
ss.SimpleUpload = function(options) {
this._settings = {
button: '',
url: '',
progressUrl: false,
multiple: false,
maxUploads: 3,
queue: true,
checkProgressInterval: 50,
keyParamName: 'APC_UPLOAD_PROGRESS',
allowedExtensions: [],
accept: '',
maxSize: false,
name: '',
data: {},
autoSubmit: true,
multipart: false,
method: 'POST',
responseType: '',
debug: false,
hoverClass: '',
focusClass: '',
disabledClass: '',
onChange: function(filename, extension) {},
onSubmit: function(filename, extension) {},
onProgress: function(pct) {},
onUpdateFileSize: function(filesize) {},
onComplete: function(filename, response) {},
onExtError: function(filename, extension) {},
onSizeError: function(filename, fileSize) {},
onError: function(filename, errorType, response) {},
startXHR: function(filename, fileSize) {},
endXHR: function(filename, fileSize) {},
startNonXHR: function(filename) {},
endNonXHR: function(filename) {}
};
ss.extendObj(this._settings, options);
this._button = ss.verifyElem(this._settings.button);
if (this._button === false) {
throw new Error("Invalid button. Make sure the element you're passing exists.");
}
if (this._settings.multiple === false) {
this._settings.maxUploads = 1;
}
this._mouseOverButton = false;
this._input = null;
this._filename = null;
this._ext = null; // file extension
this._size = null; // file size
this._file = null; // file record
this._queue = [];
this._progressBar = null;
this._progressContainer = null;
this._fileSizeBox = null;
this._activeUploads = 0;
this._disabled = false; // If disabled, clicking on button won't do anything
// True in iframe uploads if _uploadProgressKey is not null and progressUrl set
this._doProgressUpdates = false;
// Contains the currently active upload progress server keys
this._activeProgressKeys = [];
// Unique key for tracking upload progress requests in iframe uploads
// Is reset to a unique value returned by a call to uploadProgress.php after every upload (if enabled)
this._uploadProgressKey = null;
// Max # of failed progress updates requests in iframe mode
// Safeguards against potential infinite loop which could result from server error
this._maxUpdateFails = 10;
if (this._isXhrUploadSupported()) {
this._XhrIsSupported = true;
this.log('XHR upload supported');
} else {
this._XhrIsSupported = false;
this.log('XHR upload not supported, using iFrame method');
// Retrieve first upload progress key
if (this._settings.progressUrl) {
this._getUploadProgressKey();
}
}
// These calls must always be last
this._createInput();
this.enable();
this.rerouteClicks(this._button);
};
ss.SimpleUpload.prototype = {
/**
* Send data to browser console if debug is set to true
*/
log: function(str) {
if (this._settings.debug && window.console) {
console.log('[uploader] ' + str);
}
},
/**
* Replaces user data
* Note that all previously set data is entirely removed and replaced
*/
setData: function(data) {
if (typeof data === 'object') {
this._settings.data = data;
} else {
this._settings.data = {};
}
},
/**
* Designate an element as a progress bar
* The CSS width % of the element will be updated as the upload progresses
*/
setProgressBar: function(elem) {
this._progressBar = ss.verifyElem(elem);
},
/**
* Designate an element to receive a string containing file size at start of upload
* Note: Uses innerHTML so any existing child elements will be wiped out
*/
setFileSizeBox: function(elem) {
this._fileSizeBox = ss.verifyElem(elem);
},
/**
* Designate an element to be removed from DOM when upload is completed
* Useful for removing progress bar, file size, etc. after upload
*/
setProgressContainer: function(elem) {
this._progressContainer = ss.verifyElem(elem);
},
/**
* Returns number of files currently in queue
*/
getQueueSize: function() {
return this._queue.length;
},
/**
* Remove the current file from the queue and cycle to the next
*/
removeCurrent: function() {
if (this._queue.length > 0) {
this._queue.splice(0, 1); // remove the offending file
}
this._cycleQueue();
},
/**
* Disables upload functionality
*/
disable: function() {
var nodeName = this._button.nodeName.toUpperCase();
ss.addClass(this._button, this._settings.disabledClass);
this._disabled = true;
if (nodeName == 'INPUT' || nodeName == 'BUTTON') {
this._button.disabled = true;
}
// hide input
if (this._input) {
if (this._input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
this._input.parentNode.style.visibility = 'hidden';
}
}
},
/**
* Enables upload functionality
*/
enable: function() {
ss.removeClass(this._button, this._settings.disabledClass);
this._button.disabled = false;
this._disabled = false;
},
/**
* Checks whether browser supports XHR uploads
*/
_isXhrUploadSupported: function() {
var input = document.createElement('input');
input.type = 'file';
return (
'multiple' in input &&
typeof File != 'undefined' &&
typeof (new XMLHttpRequest()).upload != 'undefined');
},
/**
* Creates invisible file input
* that will hover above the button
* <div><input type='file' /></div>
*/
_createInput: function() {
var self = this,
div = document.createElement('div');
this._input = document.createElement('input');
this._input.type = 'file';
this._input.name = this._settings.name;
if (this._XhrIsSupported) {
this._input.multiple = true;
// accept attribute is supported by same browsers that support XHR uploads
if (this._settings.accept !== '') {
this._input.accept = this._settings.accept;
}
}
ss.addStyles(div, {
'display' : 'block',
'position' : 'absolute',
'overflow' : 'hidden',
'margin' : 0,
'padding' : 0,
'opacity' : 0,
'direction' : 'ltr',
'zIndex': 2147483583
});
ss.addStyles(this._input, {
'position' : 'absolute',
'right' : 0,
'margin' : 0,
'padding' : 0,
'fontSize' : '480px',
'fontFamily' : 'sans-serif',
'cursor' : 'pointer'
});
// Make sure that element opacity exists. Otherwise use IE filter
if (div.style.opacity !== '0') {
if (typeof(div.filters) == 'undefined'){
throw new Error('Opacity not supported by the browser');
}
div.style.filter = 'alpha(opacity=0)';
}
ss.addEvent(this._input, 'change', function() {
var filename,
ext,
total,
i;
if (!self._input || self._input.value === '') {
return;
}
if (!self._XhrIsSupported) {
filename = ss.getFilename(self._input.value);
ext = ss.getExt(filename);
if (false === self._settings.onChange.call(self, filename, ext)) {
return;
}
self._queue.push(self._input);
} else {
filename = ss.getFilename(self._input.files[0].name);
ext = ss.getExt(filename);
if (false === self._settings.onChange.call(self, filename, ext)) {
return;
}
total = self._input.files.length;
// Only add first file if multiple uploads aren't allowed
if (!self._settings.multiple) {
total = 1;
}
for (i = 0; i < total; i++) {
self._queue.push(self._input.files[i]);
}
}
// Remove the file input and create another after
// files have been added to queue array
self._clearInput();
// Submit when file selected if autoSubmit option is set
if (self._settings.autoSubmit) {
self.submit();
}
});
ss.addEvent(this._input, 'mouseover', function() {
if (self._mouseOverButton !== true) {
return;
}
ss.addClass(self._button, self._settings.hoverClass);
});
ss.addEvent(this._input, 'mouseout', function() {
if (self._mouseOverButton !== true) {
return;
}
ss.removeClass(self._button, self._settings.hoverClass);
ss.removeClass(self._button, self._settings.focusClass);
if (self._input.parentNode) {
self._input.parentNode.style.visibility = 'hidden';
}
});
ss.addEvent(this._input, 'focus', function() {
if (self._mouseOverButton !== true) {
return;
}
ss.addClass(self._button, self._settings.focusClass);
});
ss.addEvent(this._input, 'blur', function() {
if (self._mouseOverButton !== true) {
return;
}
ss.removeClass(self._button, self._settings.focusClass);
});
document.body.appendChild(div);
div.appendChild(this._input);
},
_clearInput: function() {
if (!this._input) {
return;
}
ss.removeClass(this._button, this._settings.hoverClass);
ss.removeClass(this._button, this._settings.focusClass);
ss.remove(this._input.parentNode);
this._input = null;
this._createInput();
},
/**
* Makes sure that when user clicks upload button,
* the this._input is clicked instead
*/
rerouteClicks: function(elem) {
var self = this;
elem = ss.verifyElem(elem);
ss.addEvent(elem, 'mouseover', function() {
if (self._disabled) {
return;
}
if (!self._input) {
self._createInput();
}
if (elem == self._button) {
self._mouseOverButton = true;
} else {
self._mouseOverButton = false;
}
ss.copyLayout(elem, self._input.parentNode);
self._input.parentNode.style.visibility = 'visible';
});
},
/**
* Creates iframe with unique name
* @return {Element} iframe
*/
_createIframe: function() {
var id = ss.getUID(),
iframe = ss.toElement('<iframe src="javascript:false;" name="' + id + '" />');
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.id = id;
return iframe;
},
/**
* Creates form, that will be submitted to iframe
* @param {Element} iframe Where to submit
* @return {Element} form
*/
_createForm: function(iframe) {
var form = ss.toElement('<form method="post" enctype="multipart/form-data"></form>');
document.body.appendChild(form);
form.style.display = 'none';
form.action = this._settings.url;
form.target = iframe.name;
return form;
},
/**
* Creates hidden input fields for the form in iframe method
* @param {String} name Input field name
* @param {String} value Value assigned to the input
* @return {Element} input
*/
_createHiddenInput: function(name, value) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
return input;
},
/**
* Completes upload request if an error is detected
*/
_errorFinish: function(errorType, errorMsg, filename, response, progressBar, fileSizeBox, progressContainer) {
this._activeUploads--;
this.log('error: '+errorMsg);
this.log('server response :'+response);
if (fileSizeBox) {
fileSizeBox.innerHTML = '';
}
if (progressContainer) {
ss.remove(progressContainer);
}
this._settings.onError.call(this, filename, errorType, response);
// Set to null to prevent memory leaks
response = null;
filename = null;
progressBar = null;
fileSizeBox = null;
progressContainer = null;
this._cycleQueue();
},
/**
* Completes upload request if the transfer was successful
*/
_finish: function(response, filename, progressBar, fileSizeBox, progressContainer) {
// Save response text in case it can't be parsed as JSON
var responseText = response;
if (this._settings.responseType.toLowerCase() == 'json') {
response = ss.parseJSON(response);
if (response === false) {
this._errorFinish('parseerror', 'Bad server response - unable to parse JSON', filename, responseText, progressBar, fileSizeBox, progressContainer);
return;
}
}
// Note: errorFinish() also decrements _activeUploads, so
// only do it after errorFinish() can no longer be called
this._activeUploads--;
this.log('server response: '+responseText);
if (fileSizeBox) {
fileSizeBox.innerHTML = '';
}
if (progressContainer) {
ss.remove(progressContainer);
}
this._settings.onComplete.call(this, filename, response);
// Set to null to prevent memory leaks
response = null;
responseText = null;
filename = null;
progressBar = null;
fileSizeBox = null;
progressContainer = null;
// Begin uploading next file in the queue
this._cycleQueue();
},
/**
* Resets file upload data and submits next file if necessary
*/
_cycleQueue: function() {
this._size = null;
this._file = null;
this._filename = null;
this._ext = null;
this._fileSizeBox = null;
this._progressBar = null;
this._progressContainer = null;
if (this._disabled) {
this.enable();
}
if (this._queue.length > 0 && this._settings.autoSubmit) {
this.submit();
}
},
/**
* Handles uploading with XHR
*/
_uploadXhr: function() {
var self = this,
settings = this._settings,
filename = this._filename,
fileSize = this._size,
fileSizeBox = this._fileSizeBox,
progressBar = this._progressBar,
progressContainer = this._progressContainer,
xhr = ss.newXHR(),
params = {},
queryURL;
if (false === settings.startXHR.call(this, filename, fileSize)) {
if (this._disabled) {
this.enable();
}
this._activeUploads--;
return;
}
if (fileSizeBox) {
fileSizeBox.innerHTML = fileSize + 'K';
}
// Add name property to query string
params[settings.name] = filename;
// We get the any additional data here after startXHR()
// in case the data was changed with setData() prior to submitting
ss.extendObj(params, settings.data);
// Build query string
queryURL = settings.url + '?' + ss.obj2string(params);
// Reset progress bars to 0%
settings.onProgress.call(this, 0);
if (progressBar) {
progressBar.style.width = '0%';
}
ss.addEvent(xhr.upload, 'progress', function(event) {
if (event.lengthComputable) {
var progress_pct = Math.round( ( event.loaded / event.total ) * 100);
settings.onProgress.call(self, progress_pct);
// Update progress bar width
if (progressBar) {
progressBar.style.width = progress_pct + '%';
}
progress_pct = null;
}
});
ss.addEvent(xhr.upload, 'error', function() {
self._errorFinish('transfererror', 'Transfer error during upload', filename, 'None', progressBar, fileSizeBox, progressContainer);
});
xhr.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status === 200 || this.status === 201) {
settings.endXHR.call(self, filename, fileSize);
self._finish(this.responseText, filename, progressBar, fileSizeBox, progressContainer);
} else {
self._errorFinish('servererror', 'Server error. Status: '+this.status, filename, this.responseText, progressBar, fileSizeBox, progressContainer);
}
}
};
xhr.open(settings.method.toUpperCase(), queryURL, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('X-File-Name', encodeURIComponent(filename));
if (settings.responseType.toLowerCase() == 'json') {
xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
}
if (settings.multipart === true) {
var formData = new FormData();
formData.append(settings.name, this._file);
this.log('commencing upload using multipart form');
xhr.send(formData);
} else {
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
this.log('commencing upload using binary stream');
xhr.send(this._file);
}
// Remove this file from the queue and begin next upload
this.removeCurrent();
},
/**
* Handles server response for iframe uploads
*/
_handleIframeResponse: function(iframe, filename, progressBar, fileSizeBox, progressContainer) {
var doc,
response;
if (!iframe.parentNode) {
return;
}
if (iframe.contentWindow) {
doc = iframe.contentWindow.document;
} else {
if (iframe.contentDocument && iframe.contentDocument.document) {
doc = iframe.contentDocument.document;
} else {
doc = iframe.contentDocument;
}
}
if (doc.body && doc.body.innerHTML === false) {
return;
}
response = doc.body.innerHTML;
ss.remove(iframe);
iframe = null;
this._finish(response, filename, progressBar, fileSizeBox, progressContainer);
},
/**
* Handles uploading with iFrame
*/
_uploadIframe: function() {
var self = this,
settings = this._settings,
checkInterval = settings.checkProgressInterval,
key = this._uploadProgressKey,
progressBar = this._progressBar,
progressContainer = this._progressContainer,
fileSizeBox = this._fileSizeBox,
filename = this._filename,
iframe = this._createIframe(),
form = this._createForm(iframe),
data;
// Upload progress key field must come before the file field
if (this._doProgressUpdates) {
var keyField = this._createHiddenInput(settings.keyParamName, key);
form.appendChild(keyField);
}