2 * jQuery File Upload User Interface Plugin 6.8.1
3 * https://github.com/blueimp/jQuery-File-Upload
5 * Copyright 2010, Sebastian Tschan
8 * Licensed under the MIT license:
9 * http://www.opensource.org/licenses/MIT
12 /*jslint nomen: true, unparam: true, regexp: true */
13 /*global define, window, document, URL, webkitURL, FileReader */
17 if (typeof define === 'function' && define.amd) {
18 // Register as an anonymous AMD module:
23 './jquery.fileupload-fp'
33 }(function ($, tmpl, loadImage) {
36 // The UI version extends the FP (file processing) version or the basic
37 // file upload widget and adds complete user interface interaction:
38 var parentWidget = ($.blueimpFP || $.blueimp).fileupload;
39 $.widget('blueimpUI.fileupload', parentWidget, {
42 // By default, files added to the widget are uploaded as soon
43 // as the user clicks on the start buttons. To enable automatic
44 // uploads, set the following option to true:
46 // The following option limits the number of files that are
47 // allowed to be uploaded using this widget:
48 maxNumberOfFiles: undefined,
49 // The maximum allowed file size:
50 maxFileSize: undefined,
51 // The minimum allowed file size:
52 minFileSize: undefined,
53 // The regular expression for allowed file types, matches
54 // against either file type or file name:
55 acceptFileTypes: /.+$/i,
56 // The regular expression to define for which files a preview
57 // image is shown, matched against the file type:
58 previewSourceFileTypes: /^image\/(gif|jpeg|png)$/,
59 // The maximum file size of images that are to be displayed as preview:
60 previewSourceMaxFileSize: 5000000, // 5MB
61 // The maximum width of the preview images:
63 // The maximum height of the preview images:
65 // By default, preview images are displayed as canvas elements
66 // if supported by the browser. Set the following option to false
67 // to always display preview images as img elements:
68 previewAsCanvas: true,
69 // The ID of the upload template:
70 uploadTemplateId: 'template-upload',
71 // The ID of the download template:
72 downloadTemplateId: 'template-download',
73 // The container for the list of files. If undefined, it is set to
74 // an element with class "files" inside of the widget element:
75 filesContainer: undefined,
76 // By default, files are appended to the files container.
77 // Set the following option to true, to prepend files instead:
79 // The expected data type of the upload response, sets the dataType
80 // option of the $.ajax upload requests:
83 // The add callback is invoked as soon as files are added to the fileupload
84 // widget (via file input selection, drag & drop or add API call).
85 // See the basic file upload widget for more information:
86 add: function (e, data) {
87 var that = $(this).data('fileupload'),
88 options = that.options,
90 $(this).fileupload('process', data).done(function () {
91 that._adjustMaxNumberOfFiles(-files.length);
92 data.isAdjusted = true;
93 data.files.valid = data.isValidated = that._validate(files);
94 data.context = that._renderUpload(files).data('data', data);
95 options.filesContainer[
96 options.prependFiles ? 'prepend' : 'append'
98 that._renderPreviews(files, data.context);
99 that._forceReflow(data.context);
100 that._transition(data.context).done(
102 if ((that._trigger('added', e, data) !== false) &&
103 (options.autoUpload || data.autoUpload) &&
104 data.autoUpload !== false && data.isValidated) {
111 // Callback for the start of each file upload request:
112 send: function (e, data) {
113 var that = $(this).data('fileupload');
114 if (!data.isValidated) {
115 if (!data.isAdjusted) {
116 that._adjustMaxNumberOfFiles(-data.files.length);
118 if (!that._validate(data.files)) {
122 if (data.context && data.dataType &&
123 data.dataType.substr(0, 6) === 'iframe') {
124 // Iframe Transport does not support progress events.
125 // In lack of an indeterminate progress bar, we set
126 // the progress to 100%, showing the full animated bar:
128 .find('.progress').addClass(
129 !$.support.transition && 'progress-animated'
133 parseInt(100, 10) + '%'
136 return that._trigger('sent', e, data);
138 // Callback for successful uploads:
139 done: function (e, data) {
140 var that = $(this).data('fileupload'),
143 data.context.each(function (index) {
144 var file = ($.isArray(data.result) &&
145 data.result[index]) || {error: 'emptyResult'};
147 that._adjustMaxNumberOfFiles(1);
149 that._transition($(this)).done(
152 template = that._renderDownload([file])
153 .css('height', node.height())
155 that._forceReflow(template);
156 that._transition(template).done(
158 data.context = $(this);
159 that._trigger('completed', e, data);
166 template = that._renderDownload(data.result)
167 .appendTo(that.options.filesContainer);
168 that._forceReflow(template);
169 that._transition(template).done(
171 data.context = $(this);
172 that._trigger('completed', e, data);
177 // Callback for failed (abort or error) uploads:
178 fail: function (e, data) {
179 var that = $(this).data('fileupload'),
181 that._adjustMaxNumberOfFiles(data.files.length);
183 data.context.each(function (index) {
184 if (data.errorThrown !== 'abort') {
185 var file = data.files[index];
186 file.error = file.error || data.errorThrown ||
188 that._transition($(this)).done(
191 template = that._renderDownload([file])
193 that._forceReflow(template);
194 that._transition(template).done(
196 data.context = $(this);
197 that._trigger('failed', e, data);
203 that._transition($(this)).done(
206 that._trigger('failed', e, data);
211 } else if (data.errorThrown !== 'abort') {
212 that._adjustMaxNumberOfFiles(-data.files.length);
213 data.context = that._renderUpload(data.files)
214 .appendTo(that.options.filesContainer)
216 that._forceReflow(data.context);
217 that._transition(data.context).done(
219 data.context = $(this);
220 that._trigger('failed', e, data);
224 that._trigger('failed', e, data);
227 // Callback for upload progress events:
228 progress: function (e, data) {
230 data.context.find('.bar').css(
232 parseInt(data.loaded / data.total * 100, 10) + '%'
236 // Callback for global upload progress events:
237 progressall: function (e, data) {
239 $this.find('.fileupload-progress')
242 parseInt(data.loaded / data.total * 100, 10) + '%'
244 .find('.progress-extended').each(function () {
246 $this.data('fileupload')
247 ._renderExtendedProgress(data)
251 // Callback for uploads start, equivalent to the global ajaxStart event:
252 start: function (e) {
253 var that = $(this).data('fileupload');
254 that._transition($(this).find('.fileupload-progress')).done(
256 that._trigger('started', e);
260 // Callback for uploads stop, equivalent to the global ajaxStop event:
262 var that = $(this).data('fileupload');
263 that._transition($(this).find('.fileupload-progress')).done(
265 $(this).find('.bar').css('width', '0%');
266 $(this).find('.progress-extended').html(' ');
267 that._trigger('stopped', e);
271 // Callback for file deletion:
272 destroy: function (e, data) {
273 var that = $(this).data('fileupload');
277 that._adjustMaxNumberOfFiles(1);
278 that._transition(data.context).done(
281 that._trigger('destroyed', e, data);
287 // Link handler, that allows to download files
288 // by drag & drop of the links to the desktop:
289 _enableDragToDesktop: function () {
291 url = link.prop('href'),
292 name = link.prop('download'),
293 type = 'application/octet-stream';
294 link.bind('dragstart', function (e) {
296 e.originalEvent.dataTransfer.setData(
298 [type, name, url].join(':')
304 _adjustMaxNumberOfFiles: function (operand) {
305 if (typeof this.options.maxNumberOfFiles === 'number') {
306 this.options.maxNumberOfFiles += operand;
307 if (this.options.maxNumberOfFiles < 1) {
308 this._disableFileInputButton();
310 this._enableFileInputButton();
315 _formatFileSize: function (bytes) {
316 if (typeof bytes !== 'number') {
319 if (bytes >= 1000000000) {
320 return (bytes / 1000000000).toFixed(2) + ' GB';
322 if (bytes >= 1000000) {
323 return (bytes / 1000000).toFixed(2) + ' MB';
325 return (bytes / 1000).toFixed(2) + ' KB';
328 _formatBitrate: function (bits) {
329 if (typeof bits !== 'number') {
332 if (bits >= 1000000000) {
333 return (bits / 1000000000).toFixed(2) + ' Gbit/s';
335 if (bits >= 1000000) {
336 return (bits / 1000000).toFixed(2) + ' Mbit/s';
339 return (bits / 1000).toFixed(2) + ' kbit/s';
341 return bits + ' bit/s';
344 _formatTime: function (seconds) {
345 var date = new Date(seconds * 1000),
346 days = parseInt(seconds / 86400, 10);
347 days = days ? days + 'd ' : '';
349 ('0' + date.getUTCHours()).slice(-2) + ':' +
350 ('0' + date.getUTCMinutes()).slice(-2) + ':' +
351 ('0' + date.getUTCSeconds()).slice(-2);
354 _formatPercentage: function (floatValue) {
355 return (floatValue * 100).toFixed(2) + ' %';
358 _renderExtendedProgress: function (data) {
359 return this._formatBitrate(data.bitrate) + ' | ' +
361 (data.total - data.loaded) * 8 / data.bitrate
363 this._formatPercentage(
364 data.loaded / data.total
366 this._formatFileSize(data.loaded) + ' / ' +
367 this._formatFileSize(data.total);
370 _hasError: function (file) {
374 // The number of added files is subtracted from
375 // maxNumberOfFiles before validation, so we check if
376 // maxNumberOfFiles is below 0 (instead of below 1):
377 if (this.options.maxNumberOfFiles < 0) {
378 return 'maxNumberOfFiles';
380 // Files are accepted if either the file type or the file name
381 // matches against the acceptFileTypes regular expression, as
382 // only browsers with support for the File API report the type:
383 if (!(this.options.acceptFileTypes.test(file.type) ||
384 this.options.acceptFileTypes.test(file.name))) {
385 return 'acceptFileTypes';
387 if (this.options.maxFileSize &&
388 file.size > this.options.maxFileSize) {
389 return 'maxFileSize';
391 if (typeof file.size === 'number' &&
392 file.size < this.options.minFileSize) {
393 return 'minFileSize';
398 _validate: function (files) {
400 valid = !!files.length;
401 $.each(files, function (index, file) {
402 file.error = that._hasError(file);
410 _renderTemplate: function (func, files) {
416 formatFileSize: this._formatFileSize,
417 options: this.options
419 if (result instanceof $) {
422 return $(this.options.templatesContainer).html(result).children();
425 _renderPreview: function (file, node) {
427 options = this.options,
429 return ((loadImage && loadImage(
433 that._forceReflow(node);
434 that._transition(node).done(function () {
435 dfd.resolveWith(node);
437 if (!$.contains(document.body, node[0])) {
438 // If the element is not part of the DOM,
439 // transition events are not triggered,
440 // so we have to resolve manually:
441 dfd.resolveWith(node);
445 maxWidth: options.previewMaxWidth,
446 maxHeight: options.previewMaxHeight,
447 canvas: options.previewAsCanvas
449 )) || dfd.resolveWith(node)) && dfd;
452 _renderPreviews: function (files, nodes) {
454 options = this.options;
455 nodes.find('.preview span').each(function (index, element) {
456 var file = files[index];
457 if (options.previewSourceFileTypes.test(file.type) &&
458 ($.type(options.previewSourceMaxFileSize) !== 'number' ||
459 file.size < options.previewSourceMaxFileSize)) {
460 that._processingQueue = that._processingQueue.pipe(function () {
461 var dfd = $.Deferred();
462 that._renderPreview(file, $(element)).done(
464 dfd.resolveWith(that);
467 return dfd.promise();
471 return this._processingQueue;
474 _renderUpload: function (files) {
475 return this._renderTemplate(
476 this.options.uploadTemplate,
481 _renderDownload: function (files) {
482 return this._renderTemplate(
483 this.options.downloadTemplate,
485 ).find('a[download]').each(this._enableDragToDesktop).end();
488 _startHandler: function (e) {
490 var button = $(this),
491 template = button.closest('.template-upload'),
492 data = template.data('data');
493 if (data && data.submit && !data.jqXHR && data.submit()) {
494 button.prop('disabled', true);
498 _cancelHandler: function (e) {
500 var template = $(this).closest('.template-upload'),
501 data = template.data('data') || {};
503 data.errorThrown = 'abort';
504 e.data.fileupload._trigger('fail', e, data);
510 _deleteHandler: function (e) {
512 var button = $(this);
513 e.data.fileupload._trigger('destroy', e, {
514 context: button.closest('.template-download'),
515 url: button.attr('data-url'),
516 type: button.attr('data-type') || 'DELETE',
517 dataType: e.data.fileupload.options.dataType
521 _forceReflow: function (node) {
522 this._reflow = $.support.transition &&
523 node.length && node[0].offsetWidth;
526 _transition: function (node) {
527 var dfd = $.Deferred();
528 if ($.support.transition && node.hasClass('fade')) {
530 $.support.transition.end,
532 // Make sure we don't respond to other transitions events
533 // in the container element, e.g. from button elements:
534 if (e.target === node[0]) {
535 node.unbind($.support.transition.end);
536 dfd.resolveWith(node);
541 node.toggleClass('in');
542 dfd.resolveWith(node);
547 _initButtonBarEventHandlers: function () {
548 var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
549 filesList = this.options.filesContainer,
550 ns = this.options.namespace;
551 fileUploadButtonBar.find('.start')
552 .bind('click.' + ns, function (e) {
554 filesList.find('.start button').click();
556 fileUploadButtonBar.find('.cancel')
557 .bind('click.' + ns, function (e) {
559 filesList.find('.cancel button').click();
561 fileUploadButtonBar.find('.delete')
562 .bind('click.' + ns, function (e) {
564 filesList.find('.delete input:checked')
565 .siblings('button').click();
566 fileUploadButtonBar.find('.toggle')
567 .prop('checked', false);
569 fileUploadButtonBar.find('.toggle')
570 .bind('change.' + ns, function (e) {
571 filesList.find('.delete input').prop(
573 $(this).is(':checked')
578 _destroyButtonBarEventHandlers: function () {
579 this.element.find('.fileupload-buttonbar button')
580 .unbind('click.' + this.options.namespace);
581 this.element.find('.fileupload-buttonbar .toggle')
582 .unbind('change.' + this.options.namespace);
585 _initEventHandlers: function () {
586 parentWidget.prototype._initEventHandlers.call(this);
587 var eventData = {fileupload: this};
588 this.options.filesContainer
591 'click.' + this.options.namespace,
597 'click.' + this.options.namespace,
603 'click.' + this.options.namespace,
607 this._initButtonBarEventHandlers();
610 _destroyEventHandlers: function () {
611 var options = this.options;
612 this._destroyButtonBarEventHandlers();
613 options.filesContainer
614 .undelegate('.start button', 'click.' + options.namespace)
615 .undelegate('.cancel button', 'click.' + options.namespace)
616 .undelegate('.delete button', 'click.' + options.namespace);
617 parentWidget.prototype._destroyEventHandlers.call(this);
620 _enableFileInputButton: function () {
621 this.element.find('.fileinput-button input')
622 .prop('disabled', false)
623 .parent().removeClass('disabled');
626 _disableFileInputButton: function () {
627 this.element.find('.fileinput-button input')
628 .prop('disabled', true)
629 .parent().addClass('disabled');
632 _initTemplates: function () {
633 var options = this.options;
634 options.templatesContainer = document.createElement(
635 options.filesContainer.prop('nodeName')
638 if (options.uploadTemplateId) {
639 options.uploadTemplate = tmpl(options.uploadTemplateId);
641 if (options.downloadTemplateId) {
642 options.downloadTemplate = tmpl(options.downloadTemplateId);
647 _initFilesContainer: function () {
648 var options = this.options;
649 if (options.filesContainer === undefined) {
650 options.filesContainer = this.element.find('.files');
651 } else if (!(options.filesContainer instanceof $)) {
652 options.filesContainer = $(options.filesContainer);
656 _initSpecialOptions: function () {
657 parentWidget.prototype._initSpecialOptions.call(this);
658 this._initFilesContainer();
659 this._initTemplates();
662 _create: function () {
663 parentWidget.prototype._create.call(this);
664 this._refreshOptionsList.push(
670 this._processingQueue = $.Deferred().resolveWith(this).promise();
671 this.process = function () {
672 return this._processingQueue;
677 enable: function () {
678 parentWidget.prototype.enable.call(this);
679 this.element.find('input, button').prop('disabled', false);
680 this._enableFileInputButton();
683 disable: function () {
684 this.element.find('input, button').prop('disabled', true);
685 this._disableFileInputButton();
686 parentWidget.prototype.disable.call(this);