2 * jQuery File Upload Plugin 5.0.2
3 * https://github.com/blueimp/jQuery-File-Upload
5 * Copyright 2010, Sebastian Tschan
8 * Licensed under the MIT license:
9 * http://creativecommons.org/licenses/MIT/
12 /*jslint nomen: true, unparam: true, regexp: true */
13 /*global document, XMLHttpRequestUpload, Blob, File, FormData, location, jQuery */
18 // The fileupload widget listens for change events on file input fields
19 // defined via fileInput setting and drop events of the given dropZone.
20 // In addition to the default jQuery Widget methods, the fileupload widget
21 // exposes the "add" and "send" methods, to add or directly send files
22 // using the fileupload API.
23 // By default, files added via file input selection, drag & drop or
24 // "add" method are uploaded immediately, but it is possible to override
25 // the "add" callback option to queue file uploads.
26 $.widget('blueimp.fileupload', {
29 // The namespace used for event handler binding on the dropZone and
30 // fileInput collections.
31 // If not set, the name of the widget ("fileupload") is used.
33 // The drop target collection, by the default the complete document.
34 // Set to null or an empty collection to disable drag & drop support:
35 dropZone: $(document),
36 // The file input field collection, that is listened for change events.
37 // If undefined, it is set to the file input fields inside
38 // of the widget element on plugin initialization.
39 // Set to null or an empty collection to disable the change listener.
41 // By default, the file input field is replaced with a clone after
42 // each input field change event. This is required for iframe transport
43 // queues and allows change events to be fired for the same file
44 // selection, but can be disabled by setting the following option to false:
45 replaceFileInput: true,
46 // The parameter name for the file form data (the request argument name).
47 // If undefined or empty, the name property of the file input field is
48 // used, or "files[]" if the file input name property is also empty:
50 // By default, each file of a selection is uploaded using an individual
51 // request for XHR type uploads. Set to false to upload file
52 // selections in one request each:
53 singleFileUploads: true,
54 // Set the following option to true to issue all file upload requests
55 // in a sequential order:
56 sequentialUploads: false,
57 // Set the following option to true to force iframe transport uploads:
58 forceIframeTransport: false,
59 // By default, XHR file uploads are sent as multipart/form-data.
60 // The iframe transport is always using multipart/form-data.
61 // Set to false to enable non-multipart XHR uploads:
63 // To upload large files in smaller chunks, set the following option
64 // to a preferred maximum chunk size. If set to 0, null or undefined,
65 // or the browser does not support the required Blob API, files will
66 // be uploaded as a whole.
67 maxChunkSize: undefined,
68 // When a non-multipart upload or a chunked multipart upload has been
69 // aborted, this option can be used to resume the upload by setting
70 // it to the size of the already uploaded bytes. This option is most
71 // useful when modifying the options object inside of the "add" or
72 // "send" callbacks, as the options are cloned for each file upload.
73 uploadedBytes: undefined,
74 // By default, failed (abort or error) file uploads are removed from the
75 // global progress calculation. Set the following option to false to
76 // prevent recalculating the global progress data:
77 recalculateProgress: true,
79 // Additional form data to be sent along with the file uploads can be set
80 // using this option, which accepts an array of objects with name and
81 // value properties, a function returning such an array, a FormData
82 // object (for XHR file uploads), or a simple object.
83 // The form of the first fileInput is given as parameter to the function:
84 formData: function (form) {
85 return form.serializeArray();
88 // The add callback is invoked as soon as files are added to the fileupload
89 // widget (via file input selection, drag & drop or add API call).
90 // If the singleFileUploads option is enabled, this callback will be
91 // called once for each file in the selection for XHR file uplaods, else
92 // once for each file selection.
93 // The upload starts when the submit method is invoked on the data parameter.
94 // The data object contains a files property holding the added files
95 // and allows to override plugin options as well as define ajax settings.
96 // Listeners for this callback can also be bound the following way:
97 // .bind('fileuploadadd', func);
98 // data.submit() returns a Promise object and allows to attach additional
99 // handlers using jQuery's Deferred callbacks:
100 // data.submit().done(func).fail(func).always(func);
101 add: function (e, data) {
106 // Callback for the start of each file upload request:
107 // send: function (e, data) {}, // .bind('fileuploadsend', func);
108 // Callback for successful uploads:
109 // done: function (e, data) {}, // .bind('fileuploaddone', func);
110 // Callback for failed (abort or error) uploads:
111 // fail: function (e, data) {}, // .bind('fileuploadfail', func);
112 // Callback for completed (success, abort or error) requests:
113 // always: function (e, data) {}, // .bind('fileuploadalways', func);
114 // Callback for upload progress events:
115 // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
116 // Callback for global upload progress events:
117 // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
118 // Callback for uploads start, equivalent to the global ajaxStart event:
119 // start: function (e) {}, // .bind('fileuploadstart', func);
120 // Callback for uploads stop, equivalent to the global ajaxStop event:
121 // stop: function (e) {}, // .bind('fileuploadstop', func);
122 // Callback for change events of the fileInput collection:
123 // change: function (e, data) {}, // .bind('fileuploadchange', func);
124 // Callback for drop events of the dropZone collection:
125 // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
126 // Callback for dragover events of the dropZone collection:
127 // dragover: function (e) {}, // .bind('fileuploaddragover', func);
129 // The plugin options are used as settings object for the ajax calls.
130 // The following are jQuery ajax settings required for the file uploads:
136 // A list of options that require a refresh after assigning a new value:
137 _refreshOptionsList: ['namespace', 'dropZone', 'fileInput'],
139 _isXHRUpload: function (options) {
140 var undef = 'undefined';
141 return !options.forceIframeTransport &&
142 typeof XMLHttpRequestUpload !== undef && typeof File !== undef &&
143 (!options.multipart || typeof FormData !== undef);
146 _getFormData: function (options) {
148 if (typeof options.formData === 'function') {
149 return options.formData(options.form);
150 } else if ($.isArray(options.formData)) {
151 return options.formData;
152 } else if (options.formData) {
154 $.each(options.formData, function (name, value) {
155 formData.push({name: name, value: value});
162 _getTotal: function (files) {
164 $.each(files, function (index, file) {
165 total += file.size || 1;
170 _onProgress: function (e, data) {
171 if (e.lengthComputable) {
172 var total = data.total || this._getTotal(data.files),
174 e.loaded / e.total * (data.chunkSize || total),
176 ) + (data.uploadedBytes || 0);
177 this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
178 data.lengthComputable = true;
179 data.loaded = loaded;
181 // Trigger a custom progress event with a total data property set
182 // to the file size(s) of the current upload and a loaded data
183 // property calculated accordingly:
184 this._trigger('progress', e, data);
185 // Trigger a global progress event for all current file uploads,
186 // including ajax calls queued for sequential file uploads:
187 this._trigger('progressall', e, {
188 lengthComputable: true,
189 loaded: this._loaded,
195 _initProgressListener: function (options) {
197 xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
198 // Accesss to the native XHR object is required to add event listeners
199 // for the upload progress event:
200 if (xhr.upload && xhr.upload.addEventListener) {
201 xhr.upload.addEventListener('progress', function (e) {
202 that._onProgress(e, options);
204 options.xhr = function () {
210 _initXHRData: function (options) {
212 file = options.files[0];
213 if (!options.multipart || options.blob) {
214 // For non-multipart uploads and chunked uploads,
215 // file meta data is not part of the request body,
216 // so we transmit this data as part of the HTTP headers.
217 // For cross domain requests, these headers must be allowed
218 // via Access-Control-Allow-Headers or removed using
219 // the beforeSend callback:
220 options.headers = $.extend(options.headers, {
221 'X-File-Name': file.name,
222 'X-File-Type': file.type,
223 'X-File-Size': file.size
226 // Non-chunked non-multipart upload:
227 options.contentType = file.type;
229 } else if (!options.multipart) {
230 // Chunked non-multipart upload:
231 options.contentType = 'application/octet-stream';
232 options.data = options.blob;
235 if (options.multipart && typeof FormData !== 'undefined') {
236 if (options.formData instanceof FormData) {
237 formData = options.formData;
239 formData = new FormData();
240 $.each(this._getFormData(options), function (index, field) {
241 formData.append(field.name, field.value);
245 formData.append(options.paramName, options.blob);
247 $.each(options.files, function (index, file) {
248 // File objects are also Blob instances.
249 // This check allows the tests to run with
251 if (file instanceof Blob) {
252 formData.append(options.paramName, file);
256 options.data = formData;
258 // Blob reference is not needed anymore, free memory:
262 _initIframeSettings: function (options) {
263 // Setting the dataType to iframe enables the iframe transport:
264 options.dataType = 'iframe ' + (options.dataType || '');
265 // The iframe transport accepts a serialized array as form data:
266 options.formData = this._getFormData(options);
269 _initDataSettings: function (options) {
270 if (this._isXHRUpload(options)) {
271 if (!this._chunkedUpload(options, true)) {
273 this._initXHRData(options);
275 this._initProgressListener(options);
278 this._initIframeSettings(options);
282 _initFormSettings: function (options) {
283 // Retrieve missing options from the input field and the
284 // associated form, if available:
285 if (!options.form || !options.form.length) {
286 options.form = $(options.fileInput.prop('form'));
288 if (!options.paramName) {
289 options.paramName = options.fileInput.prop('name') ||
293 options.url = options.form.prop('action') || location.href;
295 // The HTTP request method must be "POST" or "PUT":
296 options.type = (options.type || options.form.prop('method') || '')
298 if (options.type !== 'POST' && options.type !== 'PUT') {
299 options.type = 'POST';
303 _getAJAXSettings: function (data) {
304 var options = $.extend({}, this.options, data);
305 this._initFormSettings(options);
306 this._initDataSettings(options);
310 // Maps jqXHR callbacks to the equivalent
311 // methods of the given Promise object:
312 _enhancePromise: function (promise) {
313 promise.success = promise.done;
314 promise.error = promise.fail;
315 promise.complete = promise.always;
319 // Creates and returns a Promise object enhanced with
320 // the jqXHR methods abort, success, error and complete:
321 _getXHRPromise: function (resolveOrReject, context, args) {
322 var dfd = $.Deferred(),
323 promise = dfd.promise();
324 context = context || this.options.context || promise;
325 if (resolveOrReject === true) {
326 dfd.resolveWith(context, args);
327 } else if (resolveOrReject === false) {
328 dfd.rejectWith(context, args);
330 promise.abort = dfd.promise;
331 return this._enhancePromise(promise);
334 // Uploads a file in multiple, sequential requests
335 // by splitting the file up in multiple blob chunks.
336 // If the second parameter is true, only tests if the file
337 // should be uploaded in chunks, but does not invoke any
339 _chunkedUpload: function (options, testOnly) {
341 file = options.files[0],
343 ub = options.uploadedBytes = options.uploadedBytes || 0,
344 mcs = options.maxChunkSize || fs,
345 // Use the Blob methods with the slice implementation
346 // according to the W3C Blob API specification:
347 slice = file.webkitSlice || file.mozSlice || file.slice,
352 if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
360 file.error = 'uploadedBytes';
361 return this._getXHRPromise(false);
363 // n is the number of blobs to upload,
364 // calculated via filesize, uploaded bytes and max chunk size:
365 n = Math.ceil((fs - ub) / mcs);
366 // The chunk upload method accepting the chunk number as parameter:
367 upload = function (i) {
369 return that._getXHRPromise(true);
371 // Upload the blobs in sequential order:
372 return upload(i -= 1).pipe(function () {
373 // Clone the options object for each chunk upload:
374 var o = $.extend({}, options);
380 // Store the current chunk size, as the blob itself
381 // will be dereferenced after data processing:
382 o.chunkSize = o.blob.size;
383 // Process the upload data (the blob and potential form data):
384 that._initXHRData(o);
385 // Add progress listeners for this chunk upload:
386 that._initProgressListener(o);
387 jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
389 // Create a progress event if upload is done and
390 // no progress event has been invoked for this chunk:
392 that._onProgress($.Event('progress', {
393 lengthComputable: true,
398 options.uploadedBytes = o.uploadedBytes
404 // Return the piped Promise object, enhanced with an abort method,
405 // which is delegated to the jqXHR object of the current upload,
406 // and jqXHR callbacks mapped to the equivalent Promise methods:
408 pipe.abort = function () {
409 return jqXHR.abort();
411 return this._enhancePromise(pipe);
414 _beforeSend: function (e, data) {
415 if (this._active === 0) {
416 // the start callback is triggered when an upload starts
417 // and no other uploads are currently running,
418 // equivalent to the global ajaxStart event:
419 this._trigger('start');
422 // Initialize the global progress values:
423 this._loaded += data.uploadedBytes || 0;
424 this._total += this._getTotal(data.files);
427 _onDone: function (result, textStatus, jqXHR, options) {
428 if (!this._isXHRUpload(options)) {
429 // Create a progress event for each iframe load:
430 this._onProgress($.Event('progress', {
431 lengthComputable: true,
436 options.result = result;
437 options.textStatus = textStatus;
438 options.jqXHR = jqXHR;
439 this._trigger('done', null, options);
442 _onFail: function (jqXHR, textStatus, errorThrown, options) {
443 options.jqXHR = jqXHR;
444 options.textStatus = textStatus;
445 options.errorThrown = errorThrown;
446 this._trigger('fail', null, options);
447 if (options.recalculateProgress) {
448 // Remove the failed (error or abort) file upload from
449 // the global progress calculation:
450 this._loaded -= options.loaded || options.uploadedBytes || 0;
451 this._total -= options.total || this._getTotal(options.files);
455 _onAlways: function (result, textStatus, jqXHR, errorThrown, options) {
457 options.result = result;
458 options.textStatus = textStatus;
459 options.jqXHR = jqXHR;
460 options.errorThrown = errorThrown;
461 this._trigger('always', null, options);
462 if (this._active === 0) {
463 // The stop callback is triggered when all uploads have
464 // been completed, equivalent to the global ajaxStop event:
465 this._trigger('stop');
466 // Reset the global progress values:
467 this._loaded = this._total = 0;
471 _onSend: function (e, data) {
475 options = that._getAJAXSettings(data),
476 send = function (resolve, args) {
478 (resolve !== false &&
479 that._trigger('send', e, options) !== false &&
480 (that._chunkedUpload(options) || $.ajax(options))) ||
481 that._getXHRPromise(false, options.context, args)
482 ).done(function (result, textStatus, jqXHR) {
483 that._onDone(result, textStatus, jqXHR, options);
484 }).fail(function (jqXHR, textStatus, errorThrown) {
485 that._onFail(jqXHR, textStatus, errorThrown, options);
486 }).always(function (a1, a2, a3) {
487 if (!a3 || typeof a3 === 'string') {
488 that._onAlways(undefined, a2, a1, a3, options);
490 that._onAlways(a1, a2, a3, undefined, options);
495 this._beforeSend(e, options);
496 if (this.options.sequentialUploads) {
497 // Return the piped Promise object, enhanced with an abort method,
498 // which is delegated to the jqXHR object of the current upload,
499 // and jqXHR callbacks mapped to the equivalent Promise methods:
500 pipe = (this._sequence = this._sequence.pipe(send, send));
501 pipe.abort = function () {
503 return send(false, [undefined, 'abort', 'abort']);
505 return jqXHR.abort();
507 return this._enhancePromise(pipe);
512 _onAdd: function (e, data) {
515 options = $.extend({}, this.options, data);
516 if (options.singleFileUploads && this._isXHRUpload(options)) {
517 $.each(data.files, function (index, file) {
518 var newData = $.extend({}, data, {files: [file]});
519 newData.submit = function () {
520 return that._onSend(e, newData);
522 return (result = that._trigger('add', e, newData));
525 } else if (data.files.length) {
526 data = $.extend({}, data);
527 data.submit = function () {
528 return that._onSend(e, data);
530 return this._trigger('add', e, data);
534 // File Normalization for Gecko 1.9.1 (Firefox 3.5) support:
535 _normalizeFile: function (index, file) {
536 if (file.name === undefined && file.size === undefined) {
537 file.name = file.fileName;
538 file.size = file.fileSize;
542 _replaceFileInput: function (input) {
543 var inputClone = input.clone(true);
544 $('<form></form>').append(inputClone)[0].reset();
545 // Detaching allows to insert the fileInput on another form
546 // without loosing the file input value:
547 input.after(inputClone).detach();
548 // Replace the original file input element in the fileInput
549 // collection with the clone, which has been copied including
551 this.options.fileInput = this.options.fileInput.map(function (i, el) {
552 if (el === input[0]) {
553 return inputClone[0];
559 _onChange: function (e) {
560 var that = e.data.fileupload,
562 files: $.each($.makeArray(e.target.files), that._normalizeFile),
563 fileInput: $(e.target),
564 form: $(e.target.form)
566 if (!data.files.length) {
567 // If the files property is not available, the browser does not
568 // support the File API and we add a pseudo File object with
569 // the input value as name with path information removed:
570 data.files = [{name: e.target.value.replace(/^.*\\/, '')}];
572 // Store the form reference as jQuery data for other event handlers,
573 // as the form property is not available after replacing the file input:
574 if (data.form.length) {
575 data.fileInput.data('blueimp.fileupload.form', data.form);
577 data.form = data.fileInput.data('blueimp.fileupload.form');
579 if (that.options.replaceFileInput) {
580 that._replaceFileInput(data.fileInput);
582 if (that._trigger('change', e, data) === false ||
583 that._onAdd(e, data) === false) {
588 _onDrop: function (e) {
589 var that = e.data.fileupload,
590 dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
593 $.makeArray(dataTransfer && dataTransfer.files),
597 if (that._trigger('drop', e, data) === false ||
598 that._onAdd(e, data) === false) {
604 _onDragOver: function (e) {
605 var that = e.data.fileupload,
606 dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
607 if (that._trigger('dragover', e) === false) {
611 dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy';
616 _initEventHandlers: function () {
617 var ns = this.options.namespace || this.name;
618 this.options.dropZone
619 .bind('dragover.' + ns, {fileupload: this}, this._onDragOver)
620 .bind('drop.' + ns, {fileupload: this}, this._onDrop);
621 this.options.fileInput
622 .bind('change.' + ns, {fileupload: this}, this._onChange);
625 _destroyEventHandlers: function () {
626 var ns = this.options.namespace || this.name;
627 this.options.dropZone
628 .unbind('dragover.' + ns, this._onDragOver)
629 .unbind('drop.' + ns, this._onDrop);
630 this.options.fileInput
631 .unbind('change.' + ns, this._onChange);
634 _beforeSetOption: function (key, value) {
635 this._destroyEventHandlers();
638 _afterSetOption: function (key, value) {
639 var options = this.options;
640 if (!options.fileInput) {
641 options.fileInput = $();
643 if (!options.dropZone) {
644 options.dropZone = $();
646 this._initEventHandlers();
649 _setOption: function (key, value) {
650 var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
652 this._beforeSetOption(key, value);
654 $.Widget.prototype._setOption.call(this, key, value);
656 this._afterSetOption(key, value);
660 _create: function () {
661 var options = this.options;
662 if (options.fileInput === undefined) {
663 options.fileInput = this.element.is('input:file') ?
664 this.element : this.element.find('input:file');
665 } else if (!options.fileInput) {
666 options.fileInput = $();
668 if (!options.dropZone) {
669 options.dropZone = $();
671 this._sequence = this._getXHRPromise(true);
672 this._active = this._loaded = this._total = 0;
673 this._initEventHandlers();
676 destroy: function () {
677 this._destroyEventHandlers();
678 $.Widget.prototype.destroy.call(this);
681 enable: function () {
682 $.Widget.prototype.enable.call(this);
683 this._initEventHandlers();
686 disable: function () {
687 this._destroyEventHandlers();
688 $.Widget.prototype.disable.call(this);
691 // This method is exposed to the widget API and allows adding files
692 // using the fileupload API. The data parameter accepts an object which
693 // must have a files property and can contain additional options:
694 // .fileupload('add', {files: filesList});
695 add: function (data) {
696 if (!data || this.options.disabled) {
699 data.files = $.each($.makeArray(data.files), this._normalizeFile);
700 this._onAdd(null, data);
703 // This method is exposed to the widget API and allows sending files
704 // using the fileupload API. The data parameter accepts an object which
705 // must have a files property and can contain additional options:
706 // .fileupload('send', {files: filesList});
707 // The method returns a Promise object for the file upload call.
708 send: function (data) {
709 if (data && !this.options.disabled) {
710 data.files = $.each($.makeArray(data.files), this._normalizeFile);
711 if (data.files.length) {
712 return this._onSend(null, data);
715 return this._getXHRPromise(false, data && data.context);