jquery.fileupload.js 55 KB

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