-
Notifications
You must be signed in to change notification settings - Fork 1
/
depage-uploader.js
860 lines (770 loc) · 28.6 KB
/
depage-uploader.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
/**
* @require framework/shared/jquery-1.12.3.min.js
*
* @file depage-uploader.js
*
* Adds an upload progress bar to a file input field.
*
* Note that the file input base element must have an ID supplied.
*
* Supports:
* - XHR2 upload (supported in IE10 & Safari 5)
* - XHR1 upload (https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#In_Firefox_3.5_and_later)
* - PHP server side upload progress with APC - http://php.net/manual/en/book.apc.php or
* - NGINX server with upload-progress-module - http://wiki.nginx.org/NginxHttpUploadProgressModule
* - Fallsback to iframe with gif loader
* - Multiple file uploads
* - Drag and Drop Upload via options.$drag_area (defaults to file input)
*
* copyright (c) 2006-2012 Frank Hellenkamp [jonas@depage.net]
*
* @author Ben Wallis
*/
(function($){
if(!$.depage){
$.depage = {};
}
/**
* Uploader
*
* @param el - file input
* @param index
* @param options
*/
$.depage.uploader = function(el, index, options){
// To avoid scope issues, use 'base' instead of 'this' to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// require unique element id
if (base.el.id === ''){
// throw 'Base element has no ID';
}
// Add a reverse reference to the DOM object
base.$el.data("depage.uploader", base);
// cache the form selector
base.$form = base.$el.closest('form');
// store the APC_UPLOAD_PROGRESS hidden field // TODO insert dynamically from plugin?
base.$upload_id = null;
// remember the initial form target
base.target = base.$form.attr('target');
// plugin mode according to browser support - iframe / apc / xhr
base.mode = 'iframe';
// Cache the XHR object
base.xhrHttpRequest = new XMLHttpRequest();
// save dropped files
base.droppedFiles = [];
// {{{ init
/**
* Init
*
* Get the plugin options.
* Setup onchange handlers for file inputs.
* Add the progress bar elements.
*
* @return void
*/
base.init = function(){
base.options = $.extend({}, $.depage.uploader.defaultOptions, options);
if (base.options.src === "") {
base.options.src = base.$form.attr('action');
}
if (base.options.src === "") {
base.options.src = document.location.href;
}
if ( base.support() === 'iframe') {
// make iframe id unique // TODO enforce
base.options.iframe = base.el.name.replace(/\[\]/g, '') + '_' + index + '_' + base.options.iframe;
base.iframe.build();
}
// for multiple files input name should be an array
/*
var name = base.$el.attr('name');
if (base.$el.prop('multiple') && !name.match(/.*\[\]$/)){
base.$el.attr('name', name += '[]');
}
*/
base.addProgress();
// add file click handlers
base.$el.change(function() {
base.upload();
});
// bind cancel button if provided
if (base.options.cancel_button) {
base.$cancel_button = $('<a class="cancel-button" href="#cancel">×</a>').insertBefore(base.$el);
base.$cancel_button.click(function() {
base.cancel();
return false;
});
}
// setup custom button if provided
if (base.options.custom_button) {
base.setupCustomButton();
}
// default drag and drop for input
if (base.options.$drop_area === null) {
base.options.$drop_area = base.$el;
}
if (base.mode == "xhr") {
base.dragAndDrop();
}
};
// }}}
// {{{ support
/**
* Suport
*
* Determines if the browser XHR object supports upload.
* Sends a server request to the AJAX lander which should return an apc_enabled field.
*
* @returns {String}
*/
base.support = function(){
if (typeof(base.xhrHttpRequest.upload) !== 'undefined'){
base.mode = 'xhr';
} else {
$.ajax({
url : base.options.server_src + '?X-Progress-ID=EMPTY',
dataType: 'json',
success : function(data) {
if (data.apc_enabled){
base.mode = 'apc';
} else if (data.state == "starting"){
base.mode = 'nginx';
}
}
});
}
return base.mode;
},
// }}}
// {{{ setupCustomButton
/**
* setupCustomButton
*
* Based on http://goo.gl/uu5k6
*
*/
base.setupCustomButton = function (){
base.$el.wrap('<div class="custom-file-input-wrapper" style="position: relative;"/>');
base.$custom_button = $('<div class="custom-upload-button">upload</div>').css({
'position': 'absolute',
'z-index': 1
}).insertBefore(base.$el);
// make the fileinput transparent and positioned on top of the new button
$(base.$el).css({
'opacity': '0.1',
'filter': 'alpha(opacity=0.1)',
'display': 'block',
'text-align': 'left',
'width': base.$custom_button.outerWidth(),
'height': base.$custom_button.outerHeight(),
'position': 'absolute',
'cursor': 'pointer',
'z-index': 999
});
// for ie and opera make sure change event fires
function check_change() {
if (base.$el.val() && base.$el.val() !== base.$el.data('val')) {
base.$el.trigger('change');
}
}
base.$custom_button.addClass('custom-fileinput')
// keep file input under the cursor to steal the click (IE)
.mousemove(function(e){
base.$el.css({
'left': e.pageX - base.$custom_button.offset().left - base.$el.outerWidth() + 20,
'top': e.pageY - base.$custom_button.offset().top - base.$el.outerHeight() + 5
});
});
base.$el
// check for change (IE)
.click(function(){
base.$el.data('val', base.$el.val());
setTimeout(function(){
check_change();
}, 100);
})
.mouseover(function() {
base.$custom_button.addClass('custom-fileinput-hover');
})
.mouseout(function() {
base.$custom_button.removeClass('custom-fileinput-hover');
})
.focus(function(){
base.$custom_button.addClass('custom-fileinput-focus');
base.$el.data('val', base.$el.val());
})
.blur(function(){
base.$custom_button.addClass('custom-fileinput-blur');
check_change();
})
.bind('disable',function(){
base.$el.attr('disabled', true);
base.$custom_button.addClass('custom-fileinput-disabled');
})
.bind('enable',function(){
base.$el.removeAttr('disabled');
base.$custom_button.removeClass('custom-fileinput-disabled');
});
// match disabled state
if(base.$el.is('[disabled]')) {
base.$el.trigger('disable');
}
},
// }}}
// {{{ dragAndDrop
/**
* Setup drag and drop
*
* Implements HTML5 drag'n'drop file uploads by monitoring browser drag events
*/
base.dragAndDrop = function() {
// check browser drag and drop support
var div = document.createElement('div'); // TODO could move this to support() function
if (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div && !!window.FileReader)) {
base.options.$drop_area.addClass("has-drop-support");
$(document)
.on('dragover', function () {
base.options.$drop_area.addClass('drag-over'); return false;
})
.on('dragend', function () {
base.options.$drop_area.removeClass('drag-over');
return false;
})
.on('drop', function (e) {
if ($(e.target).is(base.options.$drop_area) || $.contains(base.options.$drop_area[0], e.target)){
base.options.$drop_area.removeClass('drag-over');
// append the dropped files to the input element (triggers upload via change event)
base.$el.prop("files", e.dataTransfer.files);
base.droppedFiles = e.dataTransfer.files;
base.upload();
}
return false;
});
}
};
// }}}
// {{{ upload()
/**
* Upload
*
* Facade for the upload call, wraps the iframe or xhr upload functions.
*
* @param fileinput
* @return void
*/
base.upload = function(fileinput){
switch(base.mode){
case 'iframe' :
case 'nginx' :
case 'apc' :
base.iframe.upload();
break;
case 'xhr' :
base.xhr.upload();
break;
}
};
// }}}
// {{{ IFRAME
/**
* Iframe Function Namespacing
*/
base.iframe = {
/*
* Hold iframe selector
*/
$iframe : null,
/*
* id for the ajax progress call
*/
timeout_id : null,
// {{{ iframe.build()
/**
* Build
*
* Creates the iframe.
* Adds a handler for the (2nd) iframe load (upload complete).
* Caches the hidden upload id field.
*
* @return null
*/
build : function() {
var $input = $('input[name=' + base.options.server_upload_key + ']');
if (!$input.length) {
$input = $('<input type="hidden" class="input-hidden" />').attr( {
name: base.options.server_upload_key,
id: base.options.server_upload_key,
value: base.options.getUniqueId()
});
// must be before file input in dom for apc to work
base.$form.prepend($input);
}
// add iframe if not present
base.iframe.$iframe = $('#' + base.options.iframe);
if (!base.iframe.$iframe.length) {
// ie name bug - http://webbugtrack.blogspot.de/2007/10/bug-235-createelement-is-broken-in-ie.html
base.iframe.$iframe = $('<iframe name="' + base.options.iframe + '" />').attr('id', base.options.iframe);
base.$form.append(base.iframe.$iframe);
}
var iframeUrl = base.options.src + (base.options.src.indexOf("?") == -1 ? "?" : "&") + "iframe=true";
base.iframe.$iframe.attr({
//name:base.options.iframe,
frameborder:0,
border:0,
src: iframeUrl,
scrolling:'no',
scrollbar:'no',
width: 0,
height: 0,
style: 'display: none'
});
base.iframe.$iframe.unbind().load(function(){ // ignore first frame load
base.iframe.$iframe.unbind().load(function(){
base.iframe.removeDepageInputs();
base.iframe.reset();
// clear ajax request timeouts
clearTimeout(base.iframe.timeout_id);
base.complete(base.iframe.$iframe.contents().find('body').html());
});
});
base.$upload_id = $('input[name=' + base.options.server_upload_key + ']');
var oldAction = base.$form.attr("action");
if (oldAction.indexOf("X-Progress-ID") == -1) {
base.$form.attr('action', oldAction + (oldAction.indexOf("?") == -1 ? "?" : "&") + "X-Progress-ID=" + base.$upload_id[0].value);
}
},
// }}}
// {{{ iframe.upload ()
/**
* Upload
*
* Submits the form to the iframe so that uploading begins.
*
* @return void
*/
upload : function() {
base.iframe.addDepageInputs();
base.$form
.attr('target', base.options.iframe)
.submit(); // TODO disable client side validation ?
base.start();
base.iframe.getProgress();
},
// }}}
// {{{ iframe.addDepageInputs()
/**
* addDepageInputs
*
* Adds the autosave inputs.
*
* @return void
*/
addDepageInputs : function() {
base.$form.append('<input type="hidden" name="formAutosave" value="true" />');
base.$form.append('<input type="hidden" name="ajax" value="true" />');
},
// }}}
// {{{ iframe.removeDepageInputs
/**
* removeDepageInputs
*
* Removes depage autosave inputs
*
* @return void
*/
removeDepageInputs : function() {
$('input[name="formAutosave"]', base.$form).remove();
$('input[name="ajax"]', base.$form).remove();
},
// }}}
// {{{ iframe.reset()
/**
* Reset
*
* Reset the frame target.
*
* @return void
*/
reset : function() {
base.$form.attr('target', base.target);
},
// }}}
// {{{ getProgress()
/**
* Get Progress
*
* If in "apc" mode starts sending the AJAX upload progress requests
* to the server AJAX lander specified by base.options.server_src,
* the lander should return a JSON percent field. If not set, or in iframe
* only mode the fallback loader is activated.
*
* @return void
*/
getProgress : function(){
if (base.mode=='apc' || base.mode=='nginx'){
$.ajax({
url : base.options.server_src + '?' + base.$upload_id.serialize() + "&X-Progress-ID=" + base.$upload_id[0].value,
dataType: 'json',
success : function(data) {
if (data.state == 'uploading') {
var percent = data.received * 100 / data.size;
base.setProgress(percent, data.received, data.size);
if (percent < 100){
base.iframe.timeout_id = setTimeout(base.iframe.getProgress, 250);
}
} else {
// 1st call in IE is not returning a percentage ?
base.iframe.timeout_id = setTimeout(base.iframe.getProgress, 250);
//base.fallback();
}
}
});
} else {
base.fallback();
}
},
// }}}
// {{{ iframe.cancel()
/**
* Cancel
*
* Cancels the iframe load
*
* @return void
*/
cancel : function(){
if (base.iframe.$iframe[0].contentWindow.document.execCommand) {
// ie
base.iframe.$iframe[0].contentWindow.document.execCommand('Stop');
} else {
// other browsers
base.iframe.$iframe[0].contentWindow.stop();
}
}
// }}}
};
// }}}
// {{{ XHR
/**
* XHR Function Namespacing
*/
base.xhr = {
// {{{ xhr.upload()
/**
* Upload
*
* Begin the XHR Upload. Handles progress and load events.
*
* return bool
*/
upload : function(){
if (base.options.max_filesize && base.options.max_filesize > base.el.filesize) {
base.error('max file size exceeded');
return false;
}
base.xhrHttpRequest.open('POST', base.options.src, true);
base.xhrHttpRequest.upload.onprogress = function(e) {
// TODO x-browser test and fallback
if (e.lengthComputable) {
base.setProgress( e.loaded * 100 / e.total, e.loaded, e.total);
}
};
base.xhrHttpRequest.onload = function(e) {
if (base.xhrHttpRequest.status == 200) {
base.complete(e.target.response);
} else {
base.error(base.xhrHttpRequest.status);
return false;
}
};
base.start();
var formData = new FormData();
var hasFiles = false;
// append the files
for (var i = 0; i < base.el.files.length; i++) {
formData.append(base.el.name, base.el.files[i]);
hasFiles = true;
}
for (var j = 0; j < base.droppedFiles.length; j++) {
formData.append(base.el.name, base.droppedFiles[j]);
hasFiles = true;
}
base.droppedFiles = [];
if (hasFiles) {
formData.append('formName', $('input[name="formName"]', base.$form).val());
formData.append('formCsrfToken', $('input[name="formCsrfToken"]', base.$form).val());
formData.append('formAutosave', 'true');
formData.append('ajax', 'true');
base.xhrHttpRequest.send(formData);
}
}
// }}}
};
// }}}
// {{{ cancel()
/**
* Cancel
*
* @return
*/
base.cancel = function(){
switch (base.mode) {
case 'xhr':
base.xhrHttpRequest.abort();
break;
case 'apc':
case 'nginx':
case 'iframe' :
base.iframe.cancel();
base.iframe.removeDepageInputs();
break;
}
base.clear();
};
// }}}
// {{{ error()
/**
* Error
*
* @return
*/
base.error = function(message){
switch (base.mode) {
case 'apc':
case 'nginx':
case 'iframe' :
base.iframe.removeDepageInputs();
break;
}
base.clear();
base.$el.trigger('error', message);
base.setTextinfo("upload error");
};
// }}}
// {{{ start()
/**
* Start
*
* Setup the upload
*
* @return void
*/
base.start = function(){
$(window).bind('unload.uploader', function() {
if (confirm(base.options.unload_message)) {
base.cancel();
}
});
base.$el.attr('disabled', true);
base.controls.progress.show();
base.setProgress(0);
base.setTextinfo("upload starting");
base.options.$drop_area.addClass("uploading");
base.$el.trigger('start');
};
// }}}
// {{{ complete()
/**
* Complete
*
* Upload complete
*
* @return void
*/
base.complete = function(response){
if (base.mode == "iframe") {
base.iframe.removeDepageInputs();
}
base.$el.trigger(base.options.complete_event, [response]);
base.options.$drop_area.removeClass("uploading");
base.setProgress(100);
base.clear();
base.setTextinfo("upload finished");
};
// }}}
// {{{ clear
/**
* Clear
*
* Called after an upload ends for whatever reason.
*
* - Clear the file input
* - Set progress to 0
* - Unbind the cancel dialogue
*
* @return void
*/
base.clear = function () {
base.$el.wrap('<form>').closest('form').get(0).reset();
base.$el.unwrap();
base.setProgress(0);
base.$el.removeAttr('disabled');
$(window).unbind('unload.uploader');
};
// }}}
// {{{ progress()
/**
* Set Progress
*
* Sets the progress percent width.
*
* @param percent
*
* @return void
*/
base.setProgress = function(percent, loaded, total){
var text = "";
base.controls.progress.prop("value", percent.toFixed(0));
if (loaded !== undefined && total !== undefined) {
text += percent.toFixed(1);
text += " % uploaded (";
text += base.bytesToSize(loaded, 1);
text += "/";
text += base.bytesToSize(total, 1);
text += ")";
}
base.setTextinfo(text);
};
// }}}
// {{{ baseToSize()
/**
* Set Progress
*
* Sets the progress percent width.
*
* @param percent
*
* @return void
*/
base.bytesToSize = function(bytes, precision) {
var kilobyte = 1024;
var megabyte = kilobyte * 1024;
var gigabyte = megabyte * 1024;
var terabyte = gigabyte * 1024;
if ((bytes >= 0) && (bytes < kilobyte)) {
return bytes + ' B ';
} else if ((bytes >= kilobyte) && (bytes < megabyte)) {
return (bytes / kilobyte).toFixed(precision) + ' KB';
} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
return (bytes / megabyte).toFixed(precision) + ' MB';
} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
return (bytes / gigabyte).toFixed(precision) + ' GB';
} else if (bytes >= terabyte) {
return (bytes / terabyte).toFixed(precision) + ' TB';
} else {
return bytes + ' B ';
}
};
// }}}
// {{{ fallback()
/**
* Fallback
*
* No upload progress can be calculated.
*
* Show a generic image gif loader.
*
* @return void
*/
base.fallback = function(){
var $img = $('<img />')
.attr({
'src' : base.options.loader_img,
'alt' : "uploading"
}).error(function(){
$img.replaceWith("uploading..."); // replace with text if not found
});
base.controls.percent.html($img);
};
// }}}
// {{{ addProgress()
/**
* addProgress
*
* Add the progress elements
*
* @return
*/
base.addProgress = function() {
base.controls = {
progress : $('<progress max="100" value="0" />').attr({
//'style' : 'display:none;'
'class' : base.options.classes.progress
}),
percent : $('<span />').attr({
'class' : base.options.classes.percent
}).width('0%'),
textinfo : $('<span />').attr({
'class' : base.options.classes.textinfo
})
};
//base.controls.progress.append(base.controls.percent);
if (base.options.$progress_container) {
base.options.$progress_container.append(base.controls.progress);
base.options.$progress_container.append(base.controls.textinfo);
} else {
base.$el.after(base.controls.progress);
base.$el.after(base.controls.textinfo);
}
};
// }}}
// {{{ setTextinfo()
/**
* setTextinfo
*
* @return
*/
base.setTextinfo = function(text) {
base.controls.textinfo.text(text);
};
// }}}
base.init();
};
/**
* Options
*
* @param classes : progress and percent element classes.
* @param iframe : iframe id / name.
* @param src : iframe source - form posted to.
* @param server_src: the AJAX lander for the APC upload progress calculation
* @param server_upload_key: the hidden file element name matches APC upload key.
* @param loader_img: the fallback image - animated gif or similar.
* @param getUniqueId: function for getting the unique APC upload ID.
* @param unload_message
* @param complete event
* @param max_filesize - max file size test used in xhr upload
* @param custom_button - selector for a css customisable file element, if false default is browser standard
* @param cancel_button - selector for a cancel button
* @param $drop_area - a selector user for receiving dropped files if supported by browser
* @param $progress_container - a selector to append the progress controls to.
*/
$.depage.uploader.defaultOptions = {
classes : {
progress: 'progress',
percent: 'percent',
textinfo: 'textinfo'
},
src: "",
iframe: 'upload_target',
server_src : 'framework/media/uploadprogress.php',
server_upload_key : 'APC_UPLOAD_PROGRESS',
loader_img : 'lib/global/images/loader.gif',
getUniqueId: function() { return new Date().getTime(); },
unload_message: 'Navigating away from the page will cancel the file upload. Do you want to continue?',
complete_event: 'complete',
max_filesize: false,
custom_button: false,
cancel_button: false,
$drop_area: null,
$progress_container: null
};
$.fn.depageUploader = function(options){
return this.each(function(index){
(new $.depage.uploader(this, index, options));
});
};
})(jQuery);
/* vim:set ft=javascript sw=4 sts=4 fdm=marker : */