jquery.fileupload.js 56 KB

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