source: pro-violet-viettel/www/deploy/20150304/assets/js/jquery.fileupload.js @ 794

Last change on this file since 794 was 782, checked in by dungnv, 10 years ago
File size: 50.9 KB
Line 
1
2/*
3 * jQuery File Upload Plugin 5.26
4 * https://github.com/blueimp/jQuery-File-Upload
5 *
6 * Copyright 2010, Sebastian Tschan
7 * https://blueimp.net
8 *
9 * Licensed under the MIT license:
10 * http://www.opensource.org/licenses/MIT
11 */
12
13/*jslint nomen: true, unparam: true, regexp: true */
14/*global define, window, document, File, Blob, FormData, location */
15
16(function (factory) {
17    'use strict';
18    if (typeof define === 'function' && define.amd) {
19        // Register as an anonymous AMD module:
20        define([
21            'jquery',
22            'jquery.ui.widget'
23        ], factory);
24    } else {
25        // Browser globals:
26        factory(window.jQuery);
27    }
28}(function ($) {
29    'use strict';
30
31    // The FileReader API is not actually used, but works as feature detection,
32    // as e.g. Safari supports XHR file uploads via the FormData API,
33    // but not non-multipart XHR file uploads:
34    $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
35    $.support.xhrFormDataFileUpload = !!window.FormData;
36
37    // The fileupload widget listens for change events on file input fields defined
38    // via fileInput setting and paste or drop events of the given dropZone.
39    // In addition to the default jQuery Widget methods, the fileupload widget
40    // exposes the "add" and "send" methods, to add or directly send files using
41    // the fileupload API.
42    // By default, files added via file input selection, paste, drag & drop or
43    // "add" method are uploaded immediately, but it is possible to override
44    // the "add" callback option to queue file uploads.
45    $.widget('blueimp.fileupload', {
46
47        options: {
48            // The drop target element(s), by the default the complete document.
49            // Set to null to disable drag & drop support:
50            dropZone: $(document),
51            // The paste target element(s), by the default the complete document.
52            // Set to null to disable paste support:
53            pasteZone: $(document),
54            // The file input field(s), that are listened to for change events.
55            // If undefined, it is set to the file input fields inside
56            // of the widget element on plugin initialization.
57            // Set to null to disable the change listener.
58            fileInput: undefined,
59            // By default, the file input field is replaced with a clone after
60            // each input field change event. This is required for iframe transport
61            // queues and allows change events to be fired for the same file
62            // selection, but can be disabled by setting the following option to false:
63            replaceFileInput: true,
64            // The parameter name for the file form data (the request argument name).
65            // If undefined or empty, the name property of the file input field is
66            // used, or "files[]" if the file input name property is also empty,
67            // can be a string or an array of strings:
68            paramName: undefined,
69            // By default, each file of a selection is uploaded using an individual
70            // request for XHR type uploads. Set to false to upload file
71            // selections in one request each:
72            singleFileUploads: true,
73            // To limit the number of files uploaded with one XHR request,
74            // set the following option to an integer greater than 0:
75            limitMultiFileUploads: undefined,
76            // Set the following option to true to issue all file upload requests
77            // in a sequential order:
78            sequentialUploads: false,
79            // To limit the number of concurrent uploads,
80            // set the following option to an integer greater than 0:
81            limitConcurrentUploads: undefined,
82            // Set the following option to true to force iframe transport uploads:
83            forceIframeTransport: false,
84            // Set the following option to the location of a redirect . on the
85            // origin server, for cross-domain iframe transport uploads:
86            redirect: undefined,
87            // The parameter name for the redirect url, sent as part of the form
88            // data and set to 'redirect' if this option is empty:
89            redirectParamName: undefined,
90            // Set the following option to the location of a postMessage window,
91            // to enable postMessage transport uploads:
92            postMessage: undefined,
93            // By default, XHR file uploads are sent as multipart/form-data.
94            // The iframe transport is always using multipart/form-data.
95            // Set to false to enable non-multipart XHR uploads:
96            multipart: true,
97            // To upload large files in smaller chunks, set the following option
98            // to a preferred maximum chunk size. If set to 0, null or undefined,
99            // or the browser does not support the required Blob API, files will
100            // be uploaded as a whole.
101            maxChunkSize: undefined,
102            // When a non-multipart upload or a chunked multipart upload has been
103            // aborted, this option can be used to resume the upload by setting
104            // it to the size of the already uploaded bytes. This option is most
105            // useful when modifying the options object inside of the "add" or
106            // "send" callbacks, as the options are cloned for each file upload.
107            uploadedBytes: undefined,
108            // By default, failed (abort or error) file uploads are removed from the
109            // global progress calculation. Set the following option to false to
110            // prevent recalculating the global progress data:
111            recalculateProgress: true,
112            // Interval in milliseconds to calculate and trigger progress events:
113            progressInterval: 100,
114            // Interval in milliseconds to calculate progress bitrate:
115            bitrateInterval: 500,
116            // By default, uploads are started automatically when adding files:
117            autoUpload: true,
118
119            // Additional form data to be sent along with the file uploads can be set
120            // using this option, which accepts an array of objects with name and
121            // value properties, a function returning such an array, a FormData
122            // object (for XHR file uploads), or a simple object.
123            // The form of the first fileInput is given as parameter to the function:
124            formData: function (form) {
125                return form.serializeArray();
126            },
127
128            // The add callback is invoked as soon as files are added to the fileupload
129            // widget (via file input selection, drag & drop, paste or add API call).
130            // If the singleFileUploads option is enabled, this callback will be
131            // called once for each file in the selection for XHR file uplaods, else
132            // once for each file selection.
133            // The upload starts when the submit method is invoked on the data parameter.
134            // The data object contains a files property holding the added files
135            // and allows to override plugin options as well as define ajax settings.
136            // Listeners for this callback can also be bound the following way:
137            // .bind('fileuploadadd', func);
138            // data.submit() returns a Promise object and allows to attach additional
139            // handlers using jQuery's Deferred callbacks:
140            // data.submit().done(func).fail(func).always(func);
141            add: function (e, data) {
142                if (data.autoUpload || (data.autoUpload !== false &&
143                        ($(this).data('blueimp-fileupload') ||
144                        $(this).data('fileupload')).options.autoUpload)) {
145                    data.submit();
146                }
147            },
148
149            // Other callbacks:
150
151            // Callback for the submit event of each file upload:
152            // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
153
154            // Callback for the start of each file upload request:
155            // send: function (e, data) {}, // .bind('fileuploadsend', func);
156
157            // Callback for successful uploads:
158            // done: function (e, data) {}, // .bind('fileuploaddone', func);
159
160            // Callback for failed (abort or error) uploads:
161            // fail: function (e, data) {}, // .bind('fileuploadfail', func);
162
163            // Callback for completed (success, abort or error) requests:
164            // always: function (e, data) {}, // .bind('fileuploadalways', func);
165
166            // Callback for upload progress events:
167            // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
168
169            // Callback for global upload progress events:
170            // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
171
172            // Callback for uploads start, equivalent to the global ajaxStart event:
173            // start: function (e) {}, // .bind('fileuploadstart', func);
174
175            // Callback for uploads stop, equivalent to the global ajaxStop event:
176            // stop: function (e) {}, // .bind('fileuploadstop', func);
177
178            // Callback for change events of the fileInput(s):
179            // change: function (e, data) {}, // .bind('fileuploadchange', func);
180
181            // Callback for paste events to the pasteZone(s):
182            // paste: function (e, data) {}, // .bind('fileuploadpaste', func);
183
184            // Callback for drop events of the dropZone(s):
185            // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
186
187            // Callback for dragover events of the dropZone(s):
188            // dragover: function (e) {}, // .bind('fileuploaddragover', func);
189
190            // Callback for the start of each chunk upload request:
191            // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);
192
193            // Callback for successful chunk uploads:
194            // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);
195
196            // Callback for failed (abort or error) chunk uploads:
197            // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);
198
199            // Callback for completed (success, abort or error) chunk upload requests:
200            // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);
201
202            // The plugin options are used as settings object for the ajax calls.
203            // The following are jQuery ajax settings required for the file uploads:
204            processData: false,
205            contentType: false,
206            cache: false
207        },
208
209        // A list of options that require a refresh after assigning a new value:
210        _refreshOptionsList: [
211            'fileInput',
212            'dropZone',
213            'pasteZone',
214            'multipart',
215            'forceIframeTransport'
216        ],
217
218        _BitrateTimer: function () {
219            this.timestamp = +(new Date());
220            this.loaded = 0;
221            this.bitrate = 0;
222            this.getBitrate = function (now, loaded, interval) {
223                var timeDiff = now - this.timestamp;
224                if (!this.bitrate || !interval || timeDiff > interval) {
225                    this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
226                    this.loaded = loaded;
227                    this.timestamp = now;
228                }
229                return this.bitrate;
230            };
231        },
232
233        _isXHRUpload: function (options) {
234            return !options.forceIframeTransport &&
235                ((!options.multipart && $.support.xhrFileUpload) ||
236                $.support.xhrFormDataFileUpload);
237        },
238
239        _getFormData: function (options) {
240            var formData;
241            if (typeof options.formData === 'function') {
242                return options.formData(options.form);
243            }
244            if ($.isArray(options.formData)) {
245                return options.formData;
246            }
247            if (options.formData) {
248                formData = [];
249                $.each(options.formData, function (name, value) {
250                    formData.push({name: name, value: value});
251                });
252                return formData;
253            }
254            return [];
255        },
256
257        _getTotal: function (files) {
258            var total = 0;
259            $.each(files, function (index, file) {
260                total += file.size || 1;
261            });
262            return total;
263        },
264
265        _initProgressObject: function (obj) {
266            obj._progress = {
267                loaded: 0,
268                total: 0,
269                bitrate: 0
270            };
271        },
272
273        _onProgress: function (e, data) {
274            if (e.lengthComputable) {
275                var now = +(new Date()),
276                    loaded;
277                if (data._time && data.progressInterval &&
278                        (now - data._time < data.progressInterval) &&
279                        e.loaded !== e.total) {
280                    return;
281                }
282                data._time = now;
283                loaded = Math.floor(
284                    e.loaded / e.total * (data.chunkSize || data._progress.total)
285                ) + (data.uploadedBytes || 0);
286                // Add the difference from the previously loaded state
287                // to the global loaded counter:
288                this._progress.loaded += (loaded - data._progress.loaded);
289                this._progress.bitrate = this._bitrateTimer.getBitrate(
290                    now,
291                    this._progress.loaded,
292                    data.bitrateInterval
293                );
294                data._progress.loaded = data.loaded = loaded;
295                data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
296                    now,
297                    loaded,
298                    data.bitrateInterval
299                );
300                // Trigger a custom progress event with a total data property set
301                // to the file size(s) of the current upload and a loaded data
302                // property calculated accordingly:
303                this._trigger('progress', e, data);
304                // Trigger a global progress event for all current file uploads,
305                // including ajax calls queued for sequential file uploads:
306                this._trigger('progressall', e, this._progress);
307            }
308        },
309
310        _initProgressListener: function (options) {
311            var that = this,
312                xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
313            // Accesss to the native XHR object is required to add event listeners
314            // for the upload progress event:
315            if (xhr.upload) {
316                $(xhr.upload).bind('progress', function (e) {
317                    var oe = e.originalEvent;
318                    // Make sure the progress event properties get copied over:
319                    e.lengthComputable = oe.lengthComputable;
320                    e.loaded = oe.loaded;
321                    e.total = oe.total;
322                    that._onProgress(e, options);
323                });
324                options.xhr = function () {
325                    return xhr;
326                };
327            }
328        },
329
330        _initXHRData: function (options) {
331            var formData,
332                file = options.files[0],
333                // Ignore non-multipart setting if not supported:
334                multipart = options.multipart || !$.support.xhrFileUpload,
335                paramName = options.paramName[0];
336            options.headers = options.headers || {};
337            if (options.contentRange) {
338                options.headers['Content-Range'] = options.contentRange;
339            }
340            if (!multipart) {
341                options.headers['Content-Disposition'] = 'attachment; filename="' +
342                    encodeURI(file.name) + '"';
343                options.contentType = file.type;
344                options.data = options.blob || file;
345            } else if ($.support.xhrFormDataFileUpload) {
346                if (options.postMessage) {
347                    // window.postMessage does not allow sending FormData
348                    // objects, so we just add the File/Blob objects to
349                    // the formData array and let the postMessage window
350                    // create the FormData object out of this array:
351                    formData = this._getFormData(options);
352                    if (options.blob) {
353                        formData.push({
354                            name: paramName,
355                            value: options.blob
356                        });
357                    } else {
358                        $.each(options.files, function (index, file) {
359                            formData.push({
360                                name: options.paramName[index] || paramName,
361                                value: file
362                            });
363                        });
364                    }
365                } else {
366                    if (options.formData instanceof FormData) {
367                        formData = options.formData;
368                    } else {
369                        formData = new FormData();
370                        $.each(this._getFormData(options), function (index, field) {
371                            formData.append(field.name, field.value);
372                        });
373                    }
374                    if (options.blob) {
375                        options.headers['Content-Disposition'] = 'attachment; filename="' +
376                            encodeURI(file.name) + '"';
377                        formData.append(paramName, options.blob, file.name);
378                    } else {
379                        $.each(options.files, function (index, file) {
380                            // Files are also Blob instances, but some browsers
381                            // (Firefox 3.6) support the File API but not Blobs.
382                            // This check allows the tests to run with
383                            // dummy objects:
384                            if ((window.Blob && file instanceof Blob) ||
385                                    (window.File && file instanceof File)) {
386                                formData.append(
387                                    options.paramName[index] || paramName,
388                                    file,
389                                    file.name
390                                );
391                            }
392                        });
393                    }
394                }
395                options.data = formData;
396            }
397            // Blob reference is not needed anymore, free memory:
398            options.blob = null;
399        },
400
401        _initIframeSettings: function (options) {
402            // Setting the dataType to iframe enables the iframe transport:
403            options.dataType = 'iframe ' + (options.dataType || '');
404            // The iframe transport accepts a serialized array as form data:
405            options.formData = this._getFormData(options);
406            // Add redirect url to form data on cross-domain uploads:
407            if (options.redirect && $('<a></a>').prop('href', options.url)
408                    .prop('host') !== location.host) {
409                options.formData.push({
410                    name: options.redirectParamName || 'redirect',
411                    value: options.redirect
412                });
413            }
414        },
415
416        _initDataSettings: function (options) {
417            if (this._isXHRUpload(options)) {
418                if (!this._chunkedUpload(options, true)) {
419                    if (!options.data) {
420                        this._initXHRData(options);
421                    }
422                    this._initProgressListener(options);
423                }
424                if (options.postMessage) {
425                    // Setting the dataType to postmessage enables the
426                    // postMessage transport:
427                    options.dataType = 'postmessage ' + (options.dataType || '');
428                }
429            } else {
430                this._initIframeSettings(options, 'iframe');
431            }
432        },
433
434        _getParamName: function (options) {
435            var fileInput = $(options.fileInput),
436                paramName = options.paramName;
437            if (!paramName) {
438                paramName = [];
439                fileInput.each(function () {
440                    var input = $(this),
441                        name = input.prop('name') || 'files[]',
442                        i = (input.prop('files') || [1]).length;
443                    while (i) {
444                        paramName.push(name);
445                        i -= 1;
446                    }
447                });
448                if (!paramName.length) {
449                    paramName = [fileInput.prop('name') || 'files[]'];
450                }
451            } else if (!$.isArray(paramName)) {
452                paramName = [paramName];
453            }
454            return paramName;
455        },
456
457        _initFormSettings: function (options) {
458            // Retrieve missing options from the input field and the
459            // associated form, if available:
460            if (!options.form || !options.form.length) {
461                options.form = $(options.fileInput.prop('form'));
462                // If the given file input doesn't have an associated form,
463                // use the default widget file input's form:
464                if (!options.form.length) {
465                    options.form = $(this.options.fileInput.prop('form'));
466                }
467            }
468            options.paramName = this._getParamName(options);
469            if (!options.url) {
470                options.url = options.form.prop('action') || location.href;
471            }
472            // The HTTP request method must be "POST" or "PUT":
473            options.type = (options.type || options.form.prop('method') || '')
474                .toUpperCase();
475            if (options.type !== 'POST' && options.type !== 'PUT' &&
476                    options.type !== 'PATCH') {
477                options.type = 'POST';
478            }
479            if (!options.formAcceptCharset) {
480                options.formAcceptCharset = options.form.attr('accept-charset');
481            }
482        },
483
484        _getAJAXSettings: function (data) {
485            var options = $.extend({}, this.options, data);
486            this._initFormSettings(options);
487            this._initDataSettings(options);
488            return options;
489        },
490
491        // jQuery 1.6 doesn't provide .state(),
492        // while jQuery 1.8+ removed .isRejected() and .isResolved():
493        _getDeferredState: function (deferred) {
494            if (deferred.state) {
495                return deferred.state();
496            }
497            if (deferred.isResolved()) {
498                return 'resolved';
499            }
500            if (deferred.isRejected()) {
501                return 'rejected';
502            }
503            return 'pending';
504        },
505
506        // Maps jqXHR callbacks to the equivalent
507        // methods of the given Promise object:
508        _enhancePromise: function (promise) {
509            promise.success = promise.done;
510            promise.error = promise.fail;
511            promise.complete = promise.always;
512            return promise;
513        },
514
515        // Creates and returns a Promise object enhanced with
516        // the jqXHR methods abort, success, error and complete:
517        _getXHRPromise: function (resolveOrReject, context, args) {
518            var dfd = $.Deferred(),
519                promise = dfd.promise();
520            context = context || this.options.context || promise;
521            if (resolveOrReject === true) {
522                dfd.resolveWith(context, args);
523            } else if (resolveOrReject === false) {
524                dfd.rejectWith(context, args);
525            }
526            promise.abort = dfd.promise;
527            return this._enhancePromise(promise);
528        },
529
530        // Adds convenience methods to the callback arguments:
531        _addConvenienceMethods: function (e, data) {
532            var that = this;
533            data.submit = function () {
534                if (this.state() !== 'pending') {
535                    data.jqXHR = this.jqXHR =
536                        (that._trigger('submit', e, this) !== false) &&
537                        that._onSend(e, this);
538                }
539                return this.jqXHR || that._getXHRPromise();
540            };
541            data.abort = function () {
542                if (this.jqXHR) {
543                    return this.jqXHR.abort();
544                }
545                return this._getXHRPromise();
546            };
547            data.state = function () {
548                if (this.jqXHR) {
549                    return that._getDeferredState(this.jqXHR);
550                }
551            };
552            data.progress = function () {
553                return this._progress;
554            };
555        },
556
557        // Parses the Range header from the server response
558        // and returns the uploaded bytes:
559        _getUploadedBytes: function (jqXHR) {
560            var range = jqXHR.getResponseHeader('Range'),
561                parts = range && range.split('-'),
562                upperBytesPos = parts && parts.length > 1 &&
563                    parseInt(parts[1], 10);
564            return upperBytesPos && upperBytesPos + 1;
565        },
566
567        // Uploads a file in multiple, sequential requests
568        // by splitting the file up in multiple blob chunks.
569        // If the second parameter is true, only tests if the file
570        // should be uploaded in chunks, but does not invoke any
571        // upload requests:
572        _chunkedUpload: function (options, testOnly) {
573            var that = this,
574                file = options.files[0],
575                fs = file.size,
576                ub = options.uploadedBytes = options.uploadedBytes || 0,
577                mcs = options.maxChunkSize || fs,
578                slice = file.slice || file.webkitSlice || file.mozSlice,
579                dfd = $.Deferred(),
580                promise = dfd.promise(),
581                jqXHR,
582                upload;
583            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
584                    options.data) {
585                return false;
586            }
587            if (testOnly) {
588                return true;
589            }
590            if (ub >= fs) {
591                file.error = 'Uploaded bytes exceed file size';
592                return this._getXHRPromise(
593                    false,
594                    options.context,
595                    [null, 'error', file.error]
596                );
597            }
598            // The chunk upload method:
599            upload = function () {
600                // Clone the options object for each chunk upload:
601                var o = $.extend({}, options),
602                    currentLoaded = o._progress.loaded;
603                o.blob = slice.call(
604                    file,
605                    ub,
606                    ub + mcs,
607                    file.type
608                );
609                // Store the current chunk size, as the blob itself
610                // will be dereferenced after data processing:
611                o.chunkSize = o.blob.size;
612                // Expose the chunk bytes position range:
613                o.contentRange = 'bytes ' + ub + '-' +
614                    (ub + o.chunkSize - 1) + '/' + fs;
615                // Process the upload data (the blob and potential form data):
616                that._initXHRData(o);
617                // Add progress listeners for this chunk upload:
618                that._initProgressListener(o);
619                jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
620                        that._getXHRPromise(false, o.context))
621                    .done(function (result, textStatus, jqXHR) {
622                        ub = that._getUploadedBytes(jqXHR) ||
623                            (ub + o.chunkSize);
624                        // Create a progress event if no final progress event
625                        // with loaded equaling total has been triggered
626                        // for this chunk:
627                        if (o._progress.loaded === currentLoaded) {
628                            that._onProgress($.Event('progress', {
629                                lengthComputable: true,
630                                loaded: ub - o.uploadedBytes,
631                                total: ub - o.uploadedBytes
632                            }), o);
633                        }
634                        options.uploadedBytes = o.uploadedBytes = ub;
635                        o.result = result;
636                        o.textStatus = textStatus;
637                        o.jqXHR = jqXHR;
638                        that._trigger('chunkdone', null, o);
639                        that._trigger('chunkalways', null, o);
640                        if (ub < fs) {
641                            // File upload not yet complete,
642                            // continue with the next chunk:
643                            upload();
644                        } else {
645                            dfd.resolveWith(
646                                o.context,
647                                [result, textStatus, jqXHR]
648                            );
649                        }
650                    })
651                    .fail(function (jqXHR, textStatus, errorThrown) {
652                        o.jqXHR = jqXHR;
653                        o.textStatus = textStatus;
654                        o.errorThrown = errorThrown;
655                        that._trigger('chunkfail', null, o);
656                        that._trigger('chunkalways', null, o);
657                        dfd.rejectWith(
658                            o.context,
659                            [jqXHR, textStatus, errorThrown]
660                        );
661                    });
662            };
663            this._enhancePromise(promise);
664            promise.abort = function () {
665                return jqXHR.abort();
666            };
667            upload();
668            return promise;
669        },
670
671        _beforeSend: function (e, data) {
672            if (this._active === 0) {
673                // the start callback is triggered when an upload starts
674                // and no other uploads are currently running,
675                // equivalent to the global ajaxStart event:
676                this._trigger('start');
677                // Set timer for global bitrate progress calculation:
678                this._bitrateTimer = new this._BitrateTimer();
679                // Reset the global progress values:
680                this._progress.loaded = this._progress.total = 0;
681                this._progress.bitrate = 0;
682            }
683            if (!data._progress) {
684                data._progress = {};
685            }
686            data._progress.loaded = data.loaded = data.uploadedBytes || 0;
687            data._progress.total = data.total = this._getTotal(data.files) || 1;
688            data._progress.bitrate = data.bitrate = 0;
689            this._active += 1;
690            // Initialize the global progress values:
691            this._progress.loaded += data.loaded;
692            this._progress.total += data.total;
693        },
694
695        _onDone: function (result, textStatus, jqXHR, options) {
696            var total = options._progress.total;
697            if (options._progress.loaded < total) {
698                // Create a progress event if no final progress event
699                // with loaded equaling total has been triggered:
700                this._onProgress($.Event('progress', {
701                    lengthComputable: true,
702                    loaded: total,
703                    total: total
704                }), options);
705            }
706            options.result = result;
707            options.result2 = result;
708            options.textStatus = textStatus;
709            options.jqXHR = jqXHR;
710            this._trigger('done', null, options);
711        },
712
713        _onFail: function (jqXHR, textStatus, errorThrown, options) {
714            options.jqXHR = jqXHR;
715            options.textStatus = textStatus;
716            options.errorThrown = errorThrown;
717            this._trigger('fail', null, options);
718            if (options.recalculateProgress) {
719                // Remove the failed (error or abort) file upload from
720                // the global progress calculation:
721                this._progress.loaded -= options._progress.loaded;
722                this._progress.total -= options._progress.total;
723            }
724        },
725
726        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
727            // jqXHRorResult, textStatus and jqXHRorError are added to the
728            // options object via done and fail callbacks
729            this._active -= 1;
730            this._trigger('always', null, options);
731            if (this._active === 0) {
732                // The stop callback is triggered when all uploads have
733                // been completed, equivalent to the global ajaxStop event:
734                this._trigger('stop');
735            }
736        },
737
738        _onSend: function (e, data) {
739            if (!data.submit) {
740                this._addConvenienceMethods(e, data);
741            }
742            var that = this,
743                jqXHR,
744                aborted,
745                slot,
746                pipe,
747                options = that._getAJAXSettings(data),
748                send = function () {
749                    that._sending += 1;
750                    // Set timer for bitrate progress calculation:
751                    options._bitrateTimer = new that._BitrateTimer();
752                    jqXHR = jqXHR || (
753                        ((aborted || that._trigger('send', e, options) === false) &&
754                        that._getXHRPromise(false, options.context, aborted)) ||
755                        that._chunkedUpload(options) || $.ajax(options)
756                    ).done(function (result, textStatus, jqXHR) {
757                        that._onDone(result, textStatus, jqXHR, options);
758                    }).fail(function (jqXHR, textStatus, errorThrown) {
759                        that._onFail(jqXHR, textStatus, errorThrown, options);
760                    }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
761                        that._sending -= 1;
762                        that._onAlways(
763                            jqXHRorResult,
764                            textStatus,
765                            jqXHRorError,
766                            options
767                        );
768                        if (options.limitConcurrentUploads &&
769                                options.limitConcurrentUploads > that._sending) {
770                            // Start the next queued upload,
771                            // that has not been aborted:
772                            var nextSlot = that._slots.shift();
773                            while (nextSlot) {
774                                if (that._getDeferredState(nextSlot) === 'pending') {
775                                    nextSlot.resolve();
776                                    break;
777                                }
778                                nextSlot = that._slots.shift();
779                            }
780                        }
781                    });
782                    return jqXHR;
783                };
784            this._beforeSend(e, options);
785            if (this.options.sequentialUploads ||
786                    (this.options.limitConcurrentUploads &&
787                    this.options.limitConcurrentUploads <= this._sending)) {
788                if (this.options.limitConcurrentUploads > 1) {
789                    slot = $.Deferred();
790                    this._slots.push(slot);
791                    pipe = slot.pipe(send);
792                } else {
793                    pipe = (this._sequence = this._sequence.pipe(send, send));
794                }
795                // Return the piped Promise object, enhanced with an abort method,
796                // which is delegated to the jqXHR object of the current upload,
797                // and jqXHR callbacks mapped to the equivalent Promise methods:
798                pipe.abort = function () {
799                    aborted = [undefined, 'abort', 'abort'];
800                    if (!jqXHR) {
801                        if (slot) {
802                            slot.rejectWith(options.context, aborted);
803                        }
804                        return send();
805                    }
806                    return jqXHR.abort();
807                };
808                return this._enhancePromise(pipe);
809            }
810            return send();
811        },
812
813        _onAdd: function (e, data) {
814            var that = this,
815                result = true,
816                options = $.extend({}, this.options, data),
817                limit = options.limitMultiFileUploads,
818                paramName = this._getParamName(options),
819                paramNameSet,
820                paramNameSlice,
821                fileSet,
822                i;
823            if (!(options.singleFileUploads || limit) ||
824                    !this._isXHRUpload(options)) {
825                fileSet = [data.files];
826                paramNameSet = [paramName];
827            } else if (!options.singleFileUploads && limit) {
828                fileSet = [];
829                paramNameSet = [];
830                for (i = 0; i < data.files.length; i += limit) {
831                    fileSet.push(data.files.slice(i, i + limit));
832                    paramNameSlice = paramName.slice(i, i + limit);
833                    if (!paramNameSlice.length) {
834                        paramNameSlice = paramName;
835                    }
836                    paramNameSet.push(paramNameSlice);
837                }
838            } else {
839                paramNameSet = paramName;
840            }
841            data.originalFiles = data.files;
842            $.each(fileSet || data.files, function (index, element) {
843                var newData = $.extend({}, data);
844                newData.files = fileSet ? element : [element];
845                newData.paramName = paramNameSet[index];
846                that._initProgressObject(newData);
847                that._addConvenienceMethods(e, newData);
848                result = that._trigger('add', e, newData);
849                return result;
850            });
851            return result;
852        },
853
854        _replaceFileInput: function (input) {
855            var inputClone = input.clone(true);
856            $('<form></form>').append(inputClone)[0].reset();
857            // Detaching allows to insert the fileInput on another form
858            // without loosing the file input value:
859            input.after(inputClone).detach();
860            // Avoid memory leaks with the detached file input:
861            $.cleanData(input.unbind('remove'));
862            // Replace the original file input element in the fileInput
863            // elements set with the clone, which has been copied including
864            // event handlers:
865            this.options.fileInput = this.options.fileInput.map(function (i, el) {
866                if (el === input[0]) {
867                    return inputClone[0];
868                }
869                return el;
870            });
871            // If the widget has been initialized on the file input itself,
872            // override this.element with the file input clone:
873            if (input[0] === this.element[0]) {
874                this.element = inputClone;
875            }
876        },
877
878        _handleFileTreeEntry: function (entry, path) {
879            var that = this,
880                dfd = $.Deferred(),
881                errorHandler = function (e) {
882                    if (e && !e.entry) {
883                        e.entry = entry;
884                    }
885                    // Since $.when returns immediately if one
886                    // Deferred is rejected, we use resolve instead.
887                    // This allows valid files and invalid items
888                    // to be returned together in one set:
889                    dfd.resolve([e]);
890                },
891                dirReader;
892            path = path || '';
893            if (entry.isFile) {
894                if (entry._file) {
895                    // Workaround for Chrome bug #149735
896                    entry._file.relativePath = path;
897                    dfd.resolve(entry._file);
898                } else {
899                    entry.file(function (file) {
900                        file.relativePath = path;
901                        dfd.resolve(file);
902                    }, errorHandler);
903                }
904            } else if (entry.isDirectory) {
905                dirReader = entry.createReader();
906                dirReader.readEntries(function (entries) {
907                    that._handleFileTreeEntries(
908                        entries,
909                        path + entry.name + '/'
910                    ).done(function (files) {
911                        dfd.resolve(files);
912                    }).fail(errorHandler);
913                }, errorHandler);
914            } else {
915                // Return an empy list for file system items
916                // other than files or directories:
917                dfd.resolve([]);
918            }
919            return dfd.promise();
920        },
921
922        _handleFileTreeEntries: function (entries, path) {
923            var that = this;
924            return $.when.apply(
925                $,
926                $.map(entries, function (entry) {
927                    return that._handleFileTreeEntry(entry, path);
928                })
929            ).pipe(function () {
930                return Array.prototype.concat.apply(
931                    [],
932                    arguments
933                );
934            });
935        },
936
937        _getDroppedFiles: function (dataTransfer) {
938            dataTransfer = dataTransfer || {};
939            var items = dataTransfer.items;
940            if (items && items.length && (items[0].webkitGetAsEntry ||
941                    items[0].getAsEntry)) {
942                return this._handleFileTreeEntries(
943                    $.map(items, function (item) {
944                        var entry;
945                        if (item.webkitGetAsEntry) {
946                            entry = item.webkitGetAsEntry();
947                            if (entry) {
948                                // Workaround for Chrome bug #149735:
949                                entry._file = item.getAsFile();
950                            }
951                            return entry;
952                        }
953                        return item.getAsEntry();
954                    })
955                );
956            }
957            return $.Deferred().resolve(
958                $.makeArray(dataTransfer.files)
959            ).promise();
960        },
961
962        _getSingleFileInputFiles: function (fileInput) {
963            fileInput = $(fileInput);
964            var entries = fileInput.prop('webkitEntries') ||
965                    fileInput.prop('entries'),
966                files,
967                value;
968            if (entries && entries.length) {
969                return this._handleFileTreeEntries(entries);
970            }
971            files = $.makeArray(fileInput.prop('files'));
972            if (!files.length) {
973                value = fileInput.prop('value');
974                if (!value) {
975                    return $.Deferred().resolve([]).promise();
976                }
977                // If the files property is not available, the browser does not
978                // support the File API and we add a pseudo File object with
979                // the input value as name with path information removed:
980                files = [{name: value.replace(/^.*\\/, '')}];
981            } else if (files[0].name === undefined && files[0].fileName) {
982                // File normalization for Safari 4 and Firefox 3:
983                $.each(files, function (index, file) {
984                    file.name = file.fileName;
985                    file.size = file.fileSize;
986                });
987            }
988            return $.Deferred().resolve(files).promise();
989        },
990
991        _getFileInputFiles: function (fileInput) {
992            if (!(fileInput instanceof $) || fileInput.length === 1) {
993                return this._getSingleFileInputFiles(fileInput);
994            }
995            return $.when.apply(
996                $,
997                $.map(fileInput, this._getSingleFileInputFiles)
998            ).pipe(function () {
999                return Array.prototype.concat.apply(
1000                    [],
1001                    arguments
1002                );
1003            });
1004        },
1005
1006        _onChange: function (e) {
1007            var that = this,
1008                data = {
1009                    fileInput: $(e.target),
1010                    form: $(e.target.form)
1011                };
1012            this._getFileInputFiles(data.fileInput).always(function (files) {
1013                data.files = files;
1014                if (that.options.replaceFileInput) {
1015                    that._replaceFileInput(data.fileInput);
1016                }
1017                if (that._trigger('change', e, data) !== false) {
1018                    that._onAdd(e, data);
1019                }
1020            });
1021        },
1022
1023        _onPaste: function (e) {
1024            var cbd = e.originalEvent.clipboardData,
1025                items = (cbd && cbd.items) || [],
1026                data = {files: []};
1027            $.each(items, function (index, item) {
1028                var file = item.getAsFile && item.getAsFile();
1029                if (file) {
1030                    data.files.push(file);
1031                }
1032            });
1033            if (this._trigger('paste', e, data) === false ||
1034                    this._onAdd(e, data) === false) {
1035                return false;
1036            }
1037        },
1038
1039        _onDrop: function (e) {
1040            var that = this,
1041                dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
1042                data = {};
1043            if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
1044                e.preventDefault();
1045            }
1046            this._getDroppedFiles(dataTransfer).always(function (files) {
1047                data.files = files;
1048                if (that._trigger('drop', e, data) !== false) {
1049                    that._onAdd(e, data);
1050                }
1051            });
1052        },
1053
1054        _onDragOver: function (e) {
1055            var dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
1056            if (this._trigger('dragover', e) === false) {
1057                return false;
1058            }
1059            if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1) {
1060                dataTransfer.dropEffect = 'copy';
1061                e.preventDefault();
1062            }
1063        },
1064
1065        _initEventHandlers: function () {
1066            if (this._isXHRUpload(this.options)) {
1067                this._on(this.options.dropZone, {
1068                    dragover: this._onDragOver,
1069                    drop: this._onDrop
1070                });
1071                this._on(this.options.pasteZone, {
1072                    paste: this._onPaste
1073                });
1074            }
1075            this._on(this.options.fileInput, {
1076                change: this._onChange
1077            });
1078        },
1079
1080        _destroyEventHandlers: function () {
1081            this._off(this.options.dropZone, 'dragover drop');
1082            this._off(this.options.pasteZone, 'paste');
1083            this._off(this.options.fileInput, 'change');
1084        },
1085
1086        _setOption: function (key, value) {
1087            var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
1088            if (refresh) {
1089                this._destroyEventHandlers();
1090            }
1091            this._super(key, value);
1092            if (refresh) {
1093                this._initSpecialOptions();
1094                this._initEventHandlers();
1095            }
1096        },
1097
1098        _initSpecialOptions: function () {
1099            var options = this.options;
1100            if (options.fileInput === undefined) {
1101                options.fileInput = this.element.is('input[type="file"]') ?
1102                        this.element : this.element.find('input[type="file"]');
1103            } else if (!(options.fileInput instanceof $)) {
1104                options.fileInput = $(options.fileInput);
1105            }
1106            if (!(options.dropZone instanceof $)) {
1107                options.dropZone = $(options.dropZone);
1108            }
1109            if (!(options.pasteZone instanceof $)) {
1110                options.pasteZone = $(options.pasteZone);
1111            }
1112        },
1113
1114        _create: function () {
1115            var options = this.options;
1116            // Initialize options set via HTML5 data-attributes:
1117            $.extend(options, $(this.element[0].cloneNode(false)).data());
1118            this._initSpecialOptions();
1119            this._slots = [];
1120            this._sequence = this._getXHRPromise(true);
1121            this._sending = this._active = 0;
1122            this._initProgressObject(this);
1123            this._initEventHandlers();
1124        },
1125
1126        // This method is exposed to the widget API and allows to query
1127        // the widget upload progress.
1128        // It returns an object with loaded, total and bitrate properties
1129        // for the running uploads:
1130        progress: function () {
1131            return this._progress;
1132        },
1133
1134        // This method is exposed to the widget API and allows adding files
1135        // using the fileupload API. The data parameter accepts an object which
1136        // must have a files property and can contain additional options:
1137        // .fileupload('add', {files: filesList});
1138        add: function (data) {
1139            var that = this;
1140            if (!data || this.options.disabled) {
1141                return;
1142            }
1143            if (data.fileInput && !data.files) {
1144                this._getFileInputFiles(data.fileInput).always(function (files) {
1145                    data.files = files;
1146                    that._onAdd(null, data);
1147                });
1148            } else {
1149                data.files = $.makeArray(data.files);
1150                this._onAdd(null, data);
1151            }
1152        },
1153
1154        // This method is exposed to the widget API and allows sending files
1155        // using the fileupload API. The data parameter accepts an object which
1156        // must have a files or fileInput property and can contain additional options:
1157        // .fileupload('send', {files: filesList});
1158        // The method returns a Promise object for the file upload call.
1159        send: function (data) {
1160            if (data && !this.options.disabled) {
1161                if (data.fileInput && !data.files) {
1162                    var that = this,
1163                        dfd = $.Deferred(),
1164                        promise = dfd.promise(),
1165                        jqXHR,
1166                        aborted;
1167                    promise.abort = function () {
1168                        aborted = true;
1169                        if (jqXHR) {
1170                            return jqXHR.abort();
1171                        }
1172                        dfd.reject(null, 'abort', 'abort');
1173                        return promise;
1174                    };
1175                    this._getFileInputFiles(data.fileInput).always(
1176                        function (files) {
1177                            if (aborted) {
1178                                return;
1179                            }
1180                            data.files = files;
1181                            jqXHR = that._onSend(null, data).then(
1182                                function (result, textStatus, jqXHR) {
1183                                    dfd.resolve(result, textStatus, jqXHR);
1184                                },
1185                                function (jqXHR, textStatus, errorThrown) {
1186                                    dfd.reject(jqXHR, textStatus, errorThrown);
1187                                }
1188                            );
1189                        }
1190                    );
1191                    return this._enhancePromise(promise);
1192                }
1193                data.files = $.makeArray(data.files);
1194                if (data.files.length) {
1195                    return this._onSend(null, data);
1196                }
1197            }
1198            return this._getXHRPromise(false, data && data.context);
1199        }
1200
1201    });
1202
1203}));
Note: See TracBrowser for help on using the repository browser.