jquery.fileupload-rails 0.0.1

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