PageSourceSearch

https://static.core77.com/javascripts/jquery.fileupload.js

js core77.com collected 2026-10-01 08:41:37 UTC 37,689 bytes, 840 lines download raw bytes

1/*
2 * jQuery File Upload Plugin 5.6
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, XMLHttpRequestUpload, Blob, File, 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(['jquery', './vendor/jquery.ui.widget', './jquery.iframe-transport'], factory);
20    } else {
21        // Browser globals:
22        factory(window.jQuery);
23    }
24}(function ($) {
25    'use strict';
26
27    // The fileupload widget listens for change events on file input fields defined
28    // via fileInput setting and paste or drop events of the given dropZone.
29    // In addition to the default jQuery Widget methods, the fileupload widget
30    // exposes the "add" and "send" methods, to add or directly send files using
31    // the fileupload API.
32    // By default, files added via file input selection, paste, drag & drop or
33    // "add" method are uploaded immediately, but it is possible to override
34    // the "add" callback option to queue file uploads.
35    $.widget('blueimp.fileupload', {
36
37        options: {
38            // The namespace used for event handler binding on the dropZone and
39            // fileInput collections.
40            // If not set, the name of the widget ("fileupload") is used.
41            namespace: undefined,
42            // The drop target collection, by the default the complete document.
43            // Set to null or an empty collection to disable drag & drop support:
44            dropZone: $(document),
45            // The file input field collection, that is listened for change events.
46            // If undefined, it is set to the file input fields inside
47            // of the widget element on plugin initialization.
48            // Set to null or an empty collection to disable the change listener.
49            fileInput: undefined,
50            // By default, the file input field is replaced with a clone after
51            // each input field change event. This is required for iframe transport
52            // queues and allows change events to be fired for the same file
53            // selection, but can be disabled by setting the following option to false:
54            replaceFileInput: true,
55            // The parameter name for the file form data (the request argument name).
56            // If undefined or empty, the name property of the file input field is
57            // used, or "files[]" if the file input name property is also empty:
58            paramName: undefined,
59            // By default, each file of a selection is uploaded using an individual
60            // request for XHR type uploads. Set to false to upload file
61            // selections in one request each:
62            singleFileUploads: true,
63            // To limit the number of files uploaded with one XHR request,
64            // set the following option to an integer greater than 0:
65            limitMultiFileUploads: undefined,
66            // Set the following option to true to issue all file upload requests
67            // in a sequential order:
68            sequentialUploads: false,
69            // To limit the number of concurrent uploads,
70            // set the following option to an integer greater than 0:
71            limitConcurrentUploads: undefined,
72            // Set the following option to true to force iframe transport uploads:
73            forceIframeTransport: false,
74            // Set the following option to the location of a postMessage window,
75            // to enable postMessage transport uploads:
76            postMessage: undefined,
77            // By default, XHR file uploads are sent as multipart/form-data.
78            // The iframe transport is always using multipart/form-data.
79            // Set to false to enable non-multipart XHR uploads:
80            multipart: true,
81            // To upload large files in smaller chunks, set the following option
82            // to a preferred maximum chunk size. If set to 0, null or undefined,
83            // or the browser does not support the required Blob API, files will
84            // be uploaded as a whole.
85            maxChunkSize: undefined,
86            // When a non-multipart upload or a chunked multipart upload has been
87            // aborted, this option can be used to resume the upload by setting
88            // it to the size of the already uploaded bytes. This option is most
89            // useful when modifying the options object inside of the "add" or
90            // "send" callbacks, as the options are cloned for each file upload.
91            uploadedBytes: undefined,
92            // By default, failed (abort or error) file uploads are removed from the
93            // global progress calculation. Set the following option to fal
93se to
94            // prevent recalculating the global progress data:
95            recalculateProgress: true,
96
97            // Additional form data to be sent along with the file uploads can be set
98            // using this option, which accepts an array of objects with name and
99            // value properties, a function returning such an array, a FormData
100            // object (for XHR file uploads), or a simple object.
101            // The form of the first fileInput is given as parameter to the function:
102            formData: function (form) {
103                return form.serializeArray();
104            },
105
106            // The add callback is invoked as soon as files are added to the fileupload
107            // widget (via file input selection, drag & drop, paste or add API call).
108            // If the singleFileUploads option is enabled, this callback will be
109            // called once for each file in the selection for XHR file uplaods, else
110            // once for each file selection.
111            // The upload starts when the submit method is invoked on the data parameter.
112            // The data object contains a files property holding the added files
113            // and allows to override plugin options as well as define ajax settings.
114            // Listeners for this callback can also be bound the following way:
115            // .bind('fileuploadadd', func);
116            // data.submit() returns a Promise object and allows to attach additional
117            // handlers using jQuery's Deferred callbacks:
118            // data.submit().done(func).fail(func).always(func);
119            add: function (e, data) {
120                data.submit();
121            },
122
123            // Other callbacks:
124            // Callback for the submit event of each file upload:
125            // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
126            // Callback for the start of each file upload request:
127            // send: function (e, data) {}, // .bind('fileuploadsend', func);
128            // Callback for successful uploads:
129            // done: function (e, data) {}, // .bind('fileuploaddone', func);
130            // Callback for failed (abort or error) uploads:
131            // fail: function (e, data) {}, // .bind('fileuploadfail', func);
132            // Callback for completed (success, abort or error) requests:
133            // always: function (e, data) {}, // .bind('fileuploadalways', func);
134            // Callback for upload progress events:
135            // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
136            // Callback for global upload progress events:
137            // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
138            // Callback for uploads start, equivalent to the global ajaxStart event:
139            // start: function (e) {}, // .bind('fileuploadstart', func);
140            // Callback for uploads stop, equivalent to the global ajaxStop event:
141            // stop: function (e) {}, // .bind('fileuploadstop', func);
142            // Callback for change events of the fileInput collection:
143            // change: function (e, data) {}, // .bind('fileuploadchange', func);
144            // Callback for paste events to the dropZone collection:
145            // paste: function (e, data) {}, // .bind('fileuploadpaste', func);
146            // Callback for drop events of the dropZone collection:
147            // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
148            // Callback for dragover events of the dropZone collection:
149            // dragover: function (e) {}, // .bind('fileuploaddragover', func);
150
151            // The plugin options are used as settings object for the ajax calls.
152            // The following are jQuery ajax settings required for the file uploads:
153            processData: false,
154            contentType: false,
155            cache: false
156        },
157
158        // A list of options that require a refresh after assigning a new value:
159        _refreshOptionsList: ['namespace', 'dropZone', 'fileInput'],
160
161        _isXHRUpload: function (options) {
162            var undef = 'undefined';
163            return !options.forceIframeTransport &&
164                typeof XMLHttpRequestUpload !== undef && typeof File !== undef &&
165                (!options.multipart || typeof FormData !== undef);
166        },
167
168        _getFormData: function (options) {
169            var formData;
170            if (typeof options.formData === 'function') {
171                return options.formData(options.form);
172            } else if ($.isArray(options.formData)) {
173                return options.formData;
174            } else if (options.formData) {
175                formData = [];
176                $.each(options.formData, function (name, value) {
177                    formData.push({name: name, value: value});
178                });
179                return formData;
180            }
181            return [];
182        },
183
184        _getTotal: function (files) {
185            var total = 0;
186            $.each(files, function (index, file) {
187                total += file.size || 1;
188            });
189            return total;
190        },
191
192        _onProgress: function (e, data) {
193            if (e.lengthComputable) {
194                var total = data.total || this._getTotal(data.files),
195                    loaded = parseInt(
196                        e.loaded / e.total * (data.chunkSize || total),
197                        10
198                    ) + (data.uploadedBytes || 0);
199                this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
200                data.lengthComputable = true;
201                data.loaded = loaded;
202                data.total = total;
203                // Trigger a custom progress event with a total data property set
204                // to the file size(s) of the current upload and a loaded data
205                // property calculated accordingly:
206                this._trigger('progress', e, data);
207                // Trigger a global progress event for all current file uploads,
208                // including ajax calls queued for sequential file uploads:
209                this._trigger('progressall', e, {
210                    lengthComputable: true,
211                    loaded: this._loaded,
212                    total: this._total
213                });
214            }
215        },
216
217        _initProgressListener: function (options) {
218            var that = this,
219                xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
220            // Accesss to the native XHR object is required to add event listeners
221            // for the upload progress event:
222            if (xhr.upload) {
223                $(xhr.upload).bind('progress', function (e) {
224                    var oe = e.originalEvent;
225                    // Make sure the progress event properties get copied over:
226                    e.lengthComputable = oe.lengthComputable;
227                    e.loaded = oe.loaded;
228                    e.total = oe.total;
229                    that._onProgress(e, options);
230                });
231                options.xhr = function () {
232                    return xhr;
233                };
234            }
235        },
236
237        _initXHRData: function (options) {
238            var formData,
239                file = options.files[0];
240            if (!options.multipart || options.blob) {
241                // For non-multipart uploads and chunked uploads,
242                // file meta data is not part of the request body,
243                // so we transmit this data as part of the HTTP headers.
244                // For cross domain requests, these headers must be allowed
245                // via Access-Control-Allow-Headers or removed using
246                // the beforeSend callback:
247                options.headers = $.extend(options.headers, {
248                    'X-File-Name': file.name,
249                    'X-File-Type': file.type,
250                    'X-File-Size': file.size
251                });
252                if (!options.blob) {
253                    // Non-chunked non-multipart upload:
254                    options.contentType = file.type;
255                    options.data = file;
256                } else if (!options.multipart) {
257                    // Chunked non-multipart upload:
258                    options.contentType = 'application/octet-stream';
259                    options.data = options.blob;
260                }
261            }
262            if (options.multipart && typeof FormData !== 'undefined') {
263                if (options.postMessage) {
264                    // window.postMessage does not allow sending FormData
265                    // objects, so we just add the File/Blob objects to
266                    // the formData array and let the postMessage window
267                    // create the FormData object out of this array:
268                    formData = this._getFormData(options);
269                    if (options.blob) {
270                        formData.push({
271                            name: options.paramName,
272                            value: options.blob
273                        });
274                    } else {
275                        $.each(options.files, function (index, file) {
276                            formData.push({
277                                name: options.paramName,
278                                value: file
279                            });
280                        });
281                    }
282                } else {
283                    if (options.formData instanceof FormData) {
284                        formData = options.formData;
285                    } else {
286                        formData = new FormData();
287                        $.each(this._getFormData(options), function (index, field) {
288                            formData.append(field.name, field.value);
289                        });
290                    }
291                    if (options.blob) {
292                        formData.append(options.paramName, options.blob);
293                    } else {
294                        $.each(options.files, function (index, file) {
295                            // File objects are also Blob instances.
296                            // This check allows the tests to run with
297                            // dummy objects:
298                            if (file instanceof Blob) {
299                                formData.append(options.paramName, file);
300                            }
301                        });
302                    }
303                }
304                options.data = formData;
305            }
306            // Blob reference is not needed anymore, free memory:
307            options.blob = null;
308        },
309
310        _initIframeSettings: function (options) {
311            // Setting the dataType to iframe enables the iframe transport:
312            options.dataType = 'iframe ' + (options.dataType || '');
313            // The iframe transport accepts a serialized array as form data:
314            options.formData = this._getFormData(options);
315        },
316
317        _initDataSettings: function (options) {
318            if (this._isXHRUpload(options)) {
319                if (!this._chunkedUpload(options, true)) {
320                    if (!options.data) {
321                        this._initXHRData(options);
322                    }
323                    this._initProgressListener(options);
324                }
325                if (options.postMessage) {
326                    // Setting the dataType to postmessage enables the
327                    // postMessage transport:
328                    options.dataType = 'postmessage ' + (options.dataType || '');
329                }
330            } else {
331                this._initIframeSettings(options, 'iframe');
332            }
333        },
334
335        _initFormSettings: function (options) {
336            // Retrieve missing options from the input field and the
337            // associated form, if available:
338            if (!options.form || !options.form.length) {
339                options.form = $(options.fileInput.prop('form'));
340            }
341            if (!options.paramName) {
342                options.paramName = options.fileInput.prop('name') ||
343                    'files[]';
344            }
345            if (!options.url) {
346                options.url = options.form.prop('action') || location.href;
347            }
348            // The HTTP request method must be "POST" or "PUT":
349            options.type = (options.type || options.form.prop('method') || '')
350                .toUpperCase();
351            if (options.type !== 'POST' && options.type !== 'PUT') {
352                options.type = 'POST';
353            }
354        },
355
356        _getAJAXSettings: function (data) {
357            var options = $.extend({}, this.options, data);
358            this._initFormSettings(options);
359            this._initDataSettings(options);
360            return options;
361        },
362
363        // Maps jqXHR callbacks to the equivalent
364        // methods of the given Promise object:
365        _enhancePromise: function (promise) {
366            promise.success = promise.done;
367            promise.error = promise.fail;
368            promise.complete = promise.always;
369            return promise;
370        },
371
372        // Creates and returns a Promise object enhanced with
373        // the jqXHR methods abort, success, error and complete:
374        _getXHRPromise: function (resolveOrReject, context, args
374) {
375            var dfd = $.Deferred(),
376                promise = dfd.promise();
377            context = context || this.options.context || promise;
378            if (resolveOrReject === true) {
379                dfd.resolveWith(context, args);
380            } else if (resolveOrReject === false) {
381                dfd.rejectWith(context, args);
382            }
383            promise.abort = dfd.promise;
384            return this._enhancePromise(promise);
385        },
386
387        // Uploads a file in multiple, sequential requests
388        // by splitting the file up in multiple blob chunks.
389        // If the second parameter is true, only tests if the file
390        // should be uploaded in chunks, but does not invoke any
391        // upload requests:
392        _chunkedUpload: function (options, testOnly) {
393            var that = this,
394                file = options.files[0],
395                fs = file.size,
396                ub = options.uploadedBytes = options.uploadedBytes || 0,
397                mcs = options.maxChunkSize || fs,
398                // Use the Blob methods with the slice implementation
399                // according to the W3C Blob API specification:
400                slice = file.webkitSlice || file.mozSlice || file.slice,
401                upload,
402                n,
403                jqXHR,
404                pipe;
405            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
406                    options.data) {
407                return false;
408            }
409            if (testOnly) {
410                return true;
411            }
412            if (ub >= fs) {
413                file.error = 'uploadedBytes';
414                return this._getXHRPromise(
415                    false,
416                    options.context,
417                    [null, 'error', file.error]
418                );
419            }
420            // n is the number of blobs to upload,
421            // calculated via filesize, uploaded bytes and max chunk size:
422            n = Math.ceil((fs - ub) / mcs);
423            // The chunk upload method accepting the chunk number as parameter:
424            upload = function (i) {
425                if (!i) {
426                    return that._getXHRPromise(true, options.context);
427                }
428                // Upload the blobs in sequential order:
429                return upload(i -= 1).pipe(function () {
430                    // Clone the options object for each chunk upload:
431                    var o = $.extend({}, options);
432                    o.blob = slice.call(
433                        file,
434                        ub + i * mcs,
435                        ub + (i + 1) * mcs
436                    );
437                    // Store the current chunk size, as the blob itself
438                    // will be dereferenced after data processing:
439                    o.chunkSize = o.blob.size;
440                    // Process the upload data (the blob and potential form data):
441                    that._initXHRData(o);
442                    // Add progress listeners for this chunk upload:
443                    that._initProgressListener(o);
444                    jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
445                        .done(function () {
446                            // Create a progress event if upload is done and
447                            // no progress event has been invoked for this chunk:
448                            if (!o.loaded) {
449                                that._onProgress($.Event('progress', {
450                                    lengthComputable: true,
451                                    loaded: o.chunkSize,
452                                    total: o.chunkSize
453                                }), o);
454                            }
455                            options.uploadedBytes = o.uploadedBytes +=
456                                o.chunkSize;
457                        });
458                    return jqXHR;
459                });
460            };
461            // Return the piped Promise object, enhanced with an abort method,
462            // which is delegated to the jqXHR object of the current upload,
463            // and jqXHR callbacks mapped to the equivalent Promise methods:
464            pipe = upload(n);
465            pipe.abort = function () {
466                return jqXHR.abort();
467            };
468            return this._enhancePromise(pipe);
469        },
470
471        _beforeSend: function (e, data) {
472            if (this._active === 0) {
473                // the start callback is triggered when an upload starts
474                // and no other uploads are currently running,
475                // equivalent to the global ajaxStart event:
476                this._trigger('start');
477            }
478            this._active += 1;
479            // Initialize the global progress values:
480            this._loaded += data.uploadedBytes || 0;
481            this._total += this._getTotal(data.files);
482        },
483
484        _onDone: function (result, textStatus, jqXHR, options) {
485            if (!this._isXHRUpload(options)) {
486                // Create a progress event for each iframe load:
487                this._onProgress($.Event('progress', {
488                    lengthComputable: true,
489                    loaded: 1,
490                    total: 1
491                }), options);
492            }
493            options.result = result;
494            options.textStatus = textStatus;
495            options.jqXHR = jqXHR;
496            this._trigger('done', null, options);
497        },
498
499        _onFail: function (jqXHR, textStatus, errorThrown, options) {
500            options.jqXHR = jqXHR;
501            options.textStatus = textStatus;
502            options.errorThrown = errorThrown;
503            this._trigger('fail', null, options);
504            if (options.recalculateProgress) {
505                // Remove the failed (error or abort) file upload from
506                // the global progress calculation:
507                this._loaded -= options.loaded || options.uploadedBytes || 0;
508                this._total -= options.total || this._getTotal(options.files);
509            }
510        },
511
512        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
513            this._active -= 1;
514            options.textStatus = textStatus;
515            if (jqXHRorError && jqXHRorError.always) {
516                options.jqXHR = jqXHRorError;
517                options.result = jqXHRorResult;
518            } else {
519                options.jqXHR = jqXHRorResult;
520                options.errorThrown = jqXHRorError;
521            }
522            this._trigger('always', null, options);
523            if (this._active === 0) {
524                // The stop callback is triggered when all uploads have
525                // been completed, equivalent to the global ajaxStop event:
526                this._trigger('stop');
527                // Reset the global progress values:
528                this._loaded = this._total = 0;
529            }
530        },
531
532        _onSend: function (e, data) {
533            var that = this,
534                jqXHR,
535                slot,
536                pipe,
537                options = that._getAJAXSettings(data),
538                send = function (resolve, args) {
539                    that._sending += 1;
540                    jqXHR = jqXHR || (
541                        (resolve !== false &&
542                        that._trigger('send', e, options) !== false &&
543                        (that._chunkedUpload(options) || $.ajax(options))) ||
544                        that._getXHRPromise(false, options.context, args)
545                    ).done(function (result, textStatus, jqXHR) {
546                        that._onDone(result, textStatus, jqXHR, options);
547                    }).fail(function (jqXHR, textStatus, errorThrown) {
548                        that._onFail(jqXHR, textStatus, errorThrown, options);
549                    }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
550                        that._sending -= 1;
551                        that._onAlways(
552                            jqXHRorResult,
553                            textStatus,
554                            jqXHRorError,
555                            options
556                        );
557                        if (options.limitConcurrentUploads &&
558                                options.limitConcurrentUploads > that._sending) {
559                            // Start the next queued upload,
560                            // that has not been aborted:
561                            var nextSlot = that._slots.shift();
562                            while (nextSlot) {
563                                if (!nextSlot.isRejected()) {
564                                    nextSlot.resolve();
565                                    break;
566                                }
567                                nextSlot = that._slots.shift();
568                            }
569                        }
570                    });
571                    return jqXHR;
572                };
573            this._beforeSend(e, options);
574            if (this.options.sequentialUploads ||
575                    (this.options.limitConcurrentUploads &&
576                    this.options.limitConcurrentUploads <= this._sending)) {
577                if (this.options.limitConcurrentUploads > 1) {
578                    slot = $.Deferred();
579                    this._slots.push(slot);
580                    pipe = slot.pipe(send);
581                } else {
582                    pipe = (this._sequence = this._sequence.pipe(send, send));
583                }
584                // Return the piped Promise object, enhanced with an abort method,
585                // which is delegated to the jqXHR object of the current upload,
586                // and jqXHR callbacks mapped to the equivalent Promise methods:
587                pipe.abort = function () {
588                    var args = [undefined, 'abort', 'abort'];
589                    if (!jqXHR) {
590                        if (slot) {
591                            slot.rejectWith(args);
592                        }
593                        return send(false, args);
594                    }
595                    return jqXHR.abort();
596                };
597                return this._enhancePromise(pipe);
598            }
599            return send();
600        },
601
602        _onAdd: function (e, data) {
603            var that = this,
604                result = true,
605                options = $.extend({}, this.options, data),
606                limit = options.limitMultiFileUploads,
607                fileSet,
608                i;
609            if (!(options.singleFileUploads || limit) ||
610                    !this._isXHRUpload(options)) {
611                fileSet = [data.files];
612            } else if (!options.singleFileUploads && limit) {
613                fileSet = [];
614                for (i = 0; i < data.files.length; i += limit) {
615                    fileSet.push(data.files.slice(i, i + limit));
616                }
617            }
618            data.originalFiles = data.files;
619            $.each(fileSet || data.files, function (index, element) {
620                var files = fileSet ? element : [element],
621                    newData = $.extend({}, data, {files: files});
622                newData.submit = function () {
623                    newData.jqXHR = this.jqXHR =
624                        (that._trigger('submit', e, this) !== false) &&
625                        that._onSend(e, this);
626                    return this.jqXHR;
627                };
628                return (result = that._trigger('add', e, newData));
629            });
630            return result;
631        },
632
633        // File Normalization for Gecko 1.9.1 (Firefox 3.5) support:
634        _normalizeFile: function (index, file) {
635            if (file.name === undefined && file.size === undefined) {
636                file.name = file.fileName;
637                file.size = file.fileSize;
638            }
639        },
640
641        _replaceFileInput: function (input) {
642            var inputClone = input.clone(true);
643            $('<form></form>').append(inputClone)[0].reset();
644            // Detaching allows to insert the fileInput on another form
645            // without loosing the file input value:
646            input.after(inputClone).detach();
647            // Avoid memory leaks with the detached file input:
648            $.cleanData(input.unbind('remove'));
649            // Replace the original file input element in the fileInput
650            // collection with the clone, which has been copied including
651            // event handlers:
652            this.options.fileInput = this.options.fileInput.map(function (i, el) {
653                if (el === input[0]) {
654                    return inputClone[0];
655                }
656                return el;
657            });
658            // If the widget has been initialized on the file input itself,
659            // override this.element with the file input clone:
660            if (input[0] === this.element[0]) {
661                this.element = inputClone;
662            }
663        },
664
665        _onChange: function (e) {
666            var that = e.data.fileupload,
667                data = {
668                    files: $.each($.makeArray(e.target.files), that._normalizeFile),
669                    fileInput: $(e.target),
670                    form: $(e.target.form)
671                };
672            if (!data.files.length) {
673                // If the files property is not available, the browser does not
674                // support the File API and we add a pseudo File object with
675                // the input value as name with path information removed:
676                data.files = [{name: e.target.value.replace(/^.*\\/, '')}];
677            }
678            if (that.options.replaceFileInput) {
679                that._replaceFileInput(data.fileInput);
680            }
681            if (that._trigger('change', e, data) === false ||
682                    that._onAdd(e, data) === false) {
683                return false;
684            }
685        },
686
687        _onPaste: function (e) {
688            var that = e.data.fileupload,
689                cbd = e.originalEvent.clipboardData,
690                items = (cbd && cbd.items) || [],
691                data = {files: []};
692            $.each(items, function (index, item) {
693                var file = item.getAsFile && item.getAsFile();
694                if (file) {
695                    data.files.push(file);
696                }
697            });
698            if (that._trigger('paste', e, data) === false ||
699                    that._onAdd(e, data) === false) {
700                return false;
701            }
702        },
703
704        _onDrop: function (e) {
705            var that = e.data.fileupload,
706                dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
707                data = {
708                    files: $.each(
709                        $.makeArray(dataTransfer && dataTransfer.files),
710                        that._normalizeFile
711                    )
712                };
713            if (that._trigger('drop', e, data) === false ||
714                    that._onAdd(e, data) === false) {
715                return false;
716            }
717            e.preventDefault();
718        },
719
720        _onDragOver: function (e) {
721            var that = e.data.fileupload,
722                dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
723            if (that._trigger('dragover', e) === false) {
724                return false;
725            }
726            if (dataTransfer) {
727                dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy';
728            }
729            e.preventDefault();
730        },
731
732        _initEventHandlers: function () {
733            var ns = this.options.namespace;
734            this.options.dropZone
735                .bind('dragover.' + ns, {fileupload: this}, this._onDragOver)
736                .bind('drop.' + ns, {fileupload: this}, this._onDrop)
737                .bind('paste.' + ns, {fileupload: this}, this._onPaste);
738            this.options.fileInput
739                .bind('change.' + ns, {fileupload: this}, this._onChange);
740        },
741
742        _destroyEventHandlers: function () {
743            var ns = this.options.namespace;
744            this.options.dropZone
745                .unbind('dragover.' + ns, this._onDragOver)
746                .unbind('drop.' + ns, this._onDrop)
747                .unbind('paste.' + ns, this._onPaste);
748            this.options.fileInput
749                .unbind('change.' + ns, this._onChange);
750        },
751
752        _beforeSetOption: function (key, value) {
753            this._destroyEventHandlers();
754        },
755
756        _afterSetOption: function (key, value) {
757            var options = this.options;
758            if (!options.fileInput) {
759                options.fileInput = $();
760            }
761            if (!options.dropZone) {
762                options.dropZone = $();
763            }
764            this._initEventHandlers();
765        },
766
767        _setOption: function (key, value) {
768            var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
769            if (refresh) {
770                this._beforeSetOption(key, value);
771            }
772            $.Widget.prototype._setOption.call(this, key, value);
773            if (refresh) {
774                this._afterSetOption(key, value);
775            }
776        },
777
778        _create: function () {
779            var options = this.options;
780            options.namespace = options.namespace || this.widgetName;
781            if (options.fileInput === undefined) {
782                options.fileInput = this.element.is('input:file') ?
783                        this.element : this.element.find('input:file');
784            } else if (!options.fileInput) {
785                options.fileInput = $();
786            }
787            if (!options.dropZone) {
788                options.dropZone = $();
789            }
790            this._slots = [];
791            this._sequence = this._getXHRPromise(true);
792            this._sending = this._active = this._loaded = this._total = 0;
793            this._initEventHandlers();
794        },
795
796        destroy: function () {
797            this._destroyEventHandlers();
798            $.Widget.prototype.destroy.call(this);
799        },
800
801        enable: function () {
802            $.Widget.prototype.enable.call(this);
803            this._initEventHandlers();
804        },
805
806        disable: function () {
807            this._destroyEventHandlers();
808            $.Widget.prototype.disable.call(this);
809        },
810
811        // This method is exposed to the widget API and allows adding files
812        // using the fileupload API. The data parameter accepts an object which
813        // must have a files property and can contain additional options:
814        // .fileupload('add', {files: filesList});
815        add: function (data) {
816            if (!data || this.options.disabled) {
817                return;
818            }
819            data.files = $.each($.makeArray(data.files), this._normalizeFile);
820            this._onAdd(null, data);
821        },
822
823        // This method is exposed to the widget API and allows sending files
824        // using the fileupload API. The data parameter accepts an object which
825        // must have a files property and can contain additional options:
826        // .fileupload('send', {files: filesList});
827        // The method returns a Promise object for the file upload call.
828        send: function (data) {
829            if (data && !this.options.disabled) {
830                data.files = $.each($.makeArray(data.files), this._normalizeFile);
831                if (data.files.length) {
832                    return this._onSend(null, data);
833                }
834            }
835            return this._getXHRPromise(false, data && data.context);
836        }
837
838    });
839
840}));

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.