source: pro-bachkim-filespace/sourcecode/assets/js/jquery.fileupload.js @ 674

Last change on this file since 674 was 674, checked in by quyenla, 10 years ago

test

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