jquery.fileupload.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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,
  390. file.name
  391. );
  392. }
  393. });
  394. }
  395. }
  396. options.data = formData;
  397. }
  398. // Blob reference is not needed anymore, free memory:
  399. options.blob = null;
  400. },
  401. _initIframeSettings: function (options) {
  402. // Setting the dataType to iframe enables the iframe transport:
  403. options.dataType = 'iframe ' + (options.dataType || '');
  404. // The iframe transport accepts a serialized array as form data:
  405. options.formData = this._getFormData(options);
  406. // Add redirect url to form data on cross-domain uploads:
  407. if (options.redirect && $('<a></a>').prop('href', options.url)
  408. .prop('host') !== location.host) {
  409. options.formData.push({
  410. name: options.redirectParamName || 'redirect',
  411. value: options.redirect
  412. });
  413. }
  414. },
  415. _initDataSettings: function (options) {
  416. if (this._isXHRUpload(options)) {
  417. if (!this._chunkedUpload(options, true)) {
  418. if (!options.data) {
  419. this._initXHRData(options);
  420. }
  421. this._initProgressListener(options);
  422. }
  423. if (options.postMessage) {
  424. // Setting the dataType to postmessage enables the
  425. // postMessage transport:
  426. options.dataType = 'postmessage ' + (options.dataType || '');
  427. }
  428. } else {
  429. this._initIframeSettings(options);
  430. }
  431. },
  432. _getParamName: function (options) {
  433. var fileInput = $(options.fileInput),
  434. paramName = options.paramName;
  435. if (!paramName) {
  436. paramName = [];
  437. fileInput.each(function () {
  438. var input = $(this),
  439. name = input.prop('name') || 'files[]',
  440. i = (input.prop('files') || [1]).length;
  441. while (i) {
  442. paramName.push(name);
  443. i -= 1;
  444. }
  445. });
  446. if (!paramName.length) {
  447. paramName = [fileInput.prop('name') || 'files[]'];
  448. }
  449. } else if (!$.isArray(paramName)) {
  450. paramName = [paramName];
  451. }
  452. return paramName;
  453. },
  454. _initFormSettings: function (options) {
  455. // Retrieve missing options from the input field and the
  456. // associated form, if available:
  457. if (!options.form || !options.form.length) {
  458. options.form = $(options.fileInput.prop('form'));
  459. // If the given file input doesn't have an associated form,
  460. // use the default widget file input's form:
  461. if (!options.form.length) {
  462. options.form = $(this.options.fileInput.prop('form'));
  463. }
  464. }
  465. options.paramName = this._getParamName(options);
  466. if (!options.url) {
  467. options.url = options.form.prop('action') || location.href;
  468. }
  469. // The HTTP request method must be "POST" or "PUT":
  470. options.type = (options.type || options.form.prop('method') || '')
  471. .toUpperCase();
  472. if (options.type !== 'POST' && options.type !== 'PUT' &&
  473. options.type !== 'PATCH') {
  474. options.type = 'POST';
  475. }
  476. if (!options.formAcceptCharset) {
  477. options.formAcceptCharset = options.form.attr('accept-charset');
  478. }
  479. },
  480. _getAJAXSettings: function (data) {
  481. var options = $.extend({}, this.options, data);
  482. this._initFormSettings(options);
  483. this._initDataSettings(options);
  484. return options;
  485. },
  486. // jQuery 1.6 doesn't provide .state(),
  487. // while jQuery 1.8+ removed .isRejected() and .isResolved():
  488. _getDeferredState: function (deferred) {
  489. if (deferred.state) {
  490. return deferred.state();
  491. }
  492. if (deferred.isResolved()) {
  493. return 'resolved';
  494. }
  495. if (deferred.isRejected()) {
  496. return 'rejected';
  497. }
  498. return 'pending';
  499. },
  500. // Maps jqXHR callbacks to the equivalent
  501. // methods of the given Promise object:
  502. _enhancePromise: function (promise) {
  503. promise.success = promise.done;
  504. promise.error = promise.fail;
  505. promise.complete = promise.always;
  506. return promise;
  507. },
  508. // Creates and returns a Promise object enhanced with
  509. // the jqXHR methods abort, success, error and complete:
  510. _getXHRPromise: function (resolveOrReject, context, args) {
  511. var dfd = $.Deferred(),
  512. promise = dfd.promise();
  513. context = context || this.options.context || promise;
  514. if (resolveOrReject === true) {
  515. dfd.resolveWith(context, args);
  516. } else if (resolveOrReject === false) {
  517. dfd.rejectWith(context, args);
  518. }
  519. promise.abort = dfd.promise;
  520. return this._enhancePromise(promise);
  521. },
  522. // Adds convenience methods to the data callback argument:
  523. _addConvenienceMethods: function (e, data) {
  524. var that = this,
  525. getPromise = function (data) {
  526. return $.Deferred().resolveWith(that, [data]).promise();
  527. };
  528. data.process = function (resolveFunc, rejectFunc) {
  529. if (resolveFunc || rejectFunc) {
  530. data._processQueue = this._processQueue =
  531. (this._processQueue || getPromise(this))
  532. .pipe(resolveFunc, rejectFunc);
  533. }
  534. return this._processQueue || getPromise(this);
  535. };
  536. data.submit = function () {
  537. if (this.state() !== 'pending') {
  538. data.jqXHR = this.jqXHR =
  539. (that._trigger('submit', e, this) !== false) &&
  540. that._onSend(e, this);
  541. }
  542. return this.jqXHR || that._getXHRPromise();
  543. };
  544. data.abort = function () {
  545. if (this.jqXHR) {
  546. return this.jqXHR.abort();
  547. }
  548. return that._getXHRPromise();
  549. };
  550. data.state = function () {
  551. if (this.jqXHR) {
  552. return that._getDeferredState(this.jqXHR);
  553. }
  554. if (this._processQueue) {
  555. return that._getDeferredState(this._processQueue);
  556. }
  557. };
  558. data.progress = function () {
  559. return this._progress;
  560. };
  561. data.response = function () {
  562. return this._response;
  563. };
  564. },
  565. // Parses the Range header from the server response
  566. // and returns the uploaded bytes:
  567. _getUploadedBytes: function (jqXHR) {
  568. var range = jqXHR.getResponseHeader('Range'),
  569. parts = range && range.split('-'),
  570. upperBytesPos = parts && parts.length > 1 &&
  571. parseInt(parts[1], 10);
  572. return upperBytesPos && upperBytesPos + 1;
  573. },
  574. // Uploads a file in multiple, sequential requests
  575. // by splitting the file up in multiple blob chunks.
  576. // If the second parameter is true, only tests if the file
  577. // should be uploaded in chunks, but does not invoke any
  578. // upload requests:
  579. _chunkedUpload: function (options, testOnly) {
  580. var that = this,
  581. file = options.files[0],
  582. fs = file.size,
  583. ub = options.uploadedBytes = options.uploadedBytes || 0,
  584. mcs = options.maxChunkSize || fs,
  585. slice = file.slice || file.webkitSlice || file.mozSlice,
  586. dfd = $.Deferred(),
  587. promise = dfd.promise(),
  588. jqXHR,
  589. upload;
  590. if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
  591. options.data) {
  592. return false;
  593. }
  594. if (testOnly) {
  595. return true;
  596. }
  597. if (ub >= fs) {
  598. file.error = options.i18n('uploadedBytes');
  599. return this._getXHRPromise(
  600. false,
  601. options.context,
  602. [null, 'error', file.error]
  603. );
  604. }
  605. // The chunk upload method:
  606. upload = function () {
  607. // Clone the options object for each chunk upload:
  608. var o = $.extend({}, options),
  609. currentLoaded = o._progress.loaded;
  610. o.blob = slice.call(
  611. file,
  612. ub,
  613. ub + mcs,
  614. file.type
  615. );
  616. // Store the current chunk size, as the blob itself
  617. // will be dereferenced after data processing:
  618. o.chunkSize = o.blob.size;
  619. // Expose the chunk bytes position range:
  620. o.contentRange = 'bytes ' + ub + '-' +
  621. (ub + o.chunkSize - 1) + '/' + fs;
  622. // Process the upload data (the blob and potential form data):
  623. that._initXHRData(o);
  624. // Add progress listeners for this chunk upload:
  625. that._initProgressListener(o);
  626. jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
  627. that._getXHRPromise(false, o.context))
  628. .done(function (result, textStatus, jqXHR) {
  629. ub = that._getUploadedBytes(jqXHR) ||
  630. (ub + o.chunkSize);
  631. // Create a progress event if no final progress event
  632. // with loaded equaling total has been triggered
  633. // for this chunk:
  634. if (currentLoaded + o.chunkSize - o._progress.loaded) {
  635. that._onProgress($.Event('progress', {
  636. lengthComputable: true,
  637. loaded: ub - o.uploadedBytes,
  638. total: ub - o.uploadedBytes
  639. }), o);
  640. }
  641. options.uploadedBytes = o.uploadedBytes = ub;
  642. o.result = result;
  643. o.textStatus = textStatus;
  644. o.jqXHR = jqXHR;
  645. that._trigger('chunkdone', null, o);
  646. that._trigger('chunkalways', null, o);
  647. if (ub < fs) {
  648. // File upload not yet complete,
  649. // continue with the next chunk:
  650. upload();
  651. } else {
  652. dfd.resolveWith(
  653. o.context,
  654. [result, textStatus, jqXHR]
  655. );
  656. }
  657. })
  658. .fail(function (jqXHR, textStatus, errorThrown) {
  659. o.jqXHR = jqXHR;
  660. o.textStatus = textStatus;
  661. o.errorThrown = errorThrown;
  662. that._trigger('chunkfail', null, o);
  663. that._trigger('chunkalways', null, o);
  664. dfd.rejectWith(
  665. o.context,
  666. [jqXHR, textStatus, errorThrown]
  667. );
  668. });
  669. };
  670. this._enhancePromise(promise);
  671. promise.abort = function () {
  672. return jqXHR.abort();
  673. };
  674. upload();
  675. return promise;
  676. },
  677. _beforeSend: function (e, data) {
  678. if (this._active === 0) {
  679. // the start callback is triggered when an upload starts
  680. // and no other uploads are currently running,
  681. // equivalent to the global ajaxStart event:
  682. this._trigger('start');
  683. // Set timer for global bitrate progress calculation:
  684. this._bitrateTimer = new this._BitrateTimer();
  685. // Reset the global progress values:
  686. this._progress.loaded = this._progress.total = 0;
  687. this._progress.bitrate = 0;
  688. }
  689. // Make sure the container objects for the .response() and
  690. // .progress() methods on the data object are available
  691. // and reset to their initial state:
  692. this._initResponseObject(data);
  693. this._initProgressObject(data);
  694. data._progress.loaded = data.loaded = data.uploadedBytes || 0;
  695. data._progress.total = data.total = this._getTotal(data.files) || 1;
  696. data._progress.bitrate = data.bitrate = 0;
  697. this._active += 1;
  698. // Initialize the global progress values:
  699. this._progress.loaded += data.loaded;
  700. this._progress.total += data.total;
  701. },
  702. _onDone: function (result, textStatus, jqXHR, options) {
  703. var total = options._progress.total,
  704. response = options._response;
  705. if (options._progress.loaded < total) {
  706. // Create a progress event if no final progress event
  707. // with loaded equaling total has been triggered:
  708. this._onProgress($.Event('progress', {
  709. lengthComputable: true,
  710. loaded: total,
  711. total: total
  712. }), options);
  713. }
  714. response.result = options.result = result;
  715. response.textStatus = options.textStatus = textStatus;
  716. response.jqXHR = options.jqXHR = jqXHR;
  717. this._trigger('done', null, options);
  718. },
  719. _onFail: function (jqXHR, textStatus, errorThrown, options) {
  720. var response = options._response;
  721. if (options.recalculateProgress) {
  722. // Remove the failed (error or abort) file upload from
  723. // the global progress calculation:
  724. this._progress.loaded -= options._progress.loaded;
  725. this._progress.total -= options._progress.total;
  726. }
  727. response.jqXHR = options.jqXHR = jqXHR;
  728. response.textStatus = options.textStatus = textStatus;
  729. response.errorThrown = options.errorThrown = errorThrown;
  730. this._trigger('fail', null, options);
  731. },
  732. _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
  733. // jqXHRorResult, textStatus and jqXHRorError are added to the
  734. // options object via done and fail callbacks
  735. this._trigger('always', null, options);
  736. },
  737. _onSend: function (e, data) {
  738. if (!data.submit) {
  739. this._addConvenienceMethods(e, data);
  740. }
  741. var that = this,
  742. jqXHR,
  743. aborted,
  744. slot,
  745. pipe,
  746. options = that._getAJAXSettings(data),
  747. send = function () {
  748. that._sending += 1;
  749. // Set timer for bitrate progress calculation:
  750. options._bitrateTimer = new that._BitrateTimer();
  751. jqXHR = jqXHR || (
  752. ((aborted || that._trigger('send', e, options) === false) &&
  753. that._getXHRPromise(false, options.context, aborted)) ||
  754. that._chunkedUpload(options) || $.ajax(options)
  755. ).done(function (result, textStatus, jqXHR) {
  756. that._onDone(result, textStatus, jqXHR, options);
  757. }).fail(function (jqXHR, textStatus, errorThrown) {
  758. that._onFail(jqXHR, textStatus, errorThrown, options);
  759. }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
  760. that._onAlways(
  761. jqXHRorResult,
  762. textStatus,
  763. jqXHRorError,
  764. options
  765. );
  766. that._sending -= 1;
  767. that._active -= 1;
  768. if (options.limitConcurrentUploads &&
  769. options.limitConcurrentUploads > that._sending) {
  770. // Start the next queued upload,
  771. // that has not been aborted:
  772. var nextSlot = that._slots.shift();
  773. while (nextSlot) {
  774. if (that._getDeferredState(nextSlot) === 'pending') {
  775. nextSlot.resolve();
  776. break;
  777. }
  778. nextSlot = that._slots.shift();
  779. }
  780. }
  781. if (that._active === 0) {
  782. // The stop callback is triggered when all uploads have
  783. // been completed, equivalent to the global ajaxStop event:
  784. that._trigger('stop');
  785. }
  786. });
  787. return jqXHR;
  788. };
  789. this._beforeSend(e, options);
  790. if (this.options.sequentialUploads ||
  791. (this.options.limitConcurrentUploads &&
  792. this.options.limitConcurrentUploads <= this._sending)) {
  793. if (this.options.limitConcurrentUploads > 1) {
  794. slot = $.Deferred();
  795. this._slots.push(slot);
  796. pipe = slot.pipe(send);
  797. } else {
  798. pipe = (this._sequence = this._sequence.pipe(send, send));
  799. }
  800. // Return the piped Promise object, enhanced with an abort method,
  801. // which is delegated to the jqXHR object of the current upload,
  802. // and jqXHR callbacks mapped to the equivalent Promise methods:
  803. pipe.abort = function () {
  804. aborted = [undefined, 'abort', 'abort'];
  805. if (!jqXHR) {
  806. if (slot) {
  807. slot.rejectWith(options.context, aborted);
  808. }
  809. return send();
  810. }
  811. return jqXHR.abort();
  812. };
  813. return this._enhancePromise(pipe);
  814. }
  815. return send();
  816. },
  817. _onAdd: function (e, data) {
  818. var that = this,
  819. result = true,
  820. options = $.extend({}, this.options, data),
  821. limit = options.limitMultiFileUploads,
  822. paramName = this._getParamName(options),
  823. paramNameSet,
  824. paramNameSlice,
  825. fileSet,
  826. i;
  827. if (!(options.singleFileUploads || limit) ||
  828. !this._isXHRUpload(options)) {
  829. fileSet = [data.files];
  830. paramNameSet = [paramName];
  831. } else if (!options.singleFileUploads && limit) {
  832. fileSet = [];
  833. paramNameSet = [];
  834. for (i = 0; i < data.files.length; i += limit) {
  835. fileSet.push(data.files.slice(i, i + limit));
  836. paramNameSlice = paramName.slice(i, i + limit);
  837. if (!paramNameSlice.length) {
  838. paramNameSlice = paramName;
  839. }
  840. paramNameSet.push(paramNameSlice);
  841. }
  842. } else {
  843. paramNameSet = paramName;
  844. }
  845. data.originalFiles = data.files;
  846. $.each(fileSet || data.files, function (index, element) {
  847. var newData = $.extend({}, data);
  848. newData.files = fileSet ? element : [element];
  849. newData.paramName = paramNameSet[index];
  850. that._initResponseObject(newData);
  851. that._initProgressObject(newData);
  852. that._addConvenienceMethods(e, newData);
  853. result = that._trigger('add', e, newData);
  854. return result;
  855. });
  856. return result;
  857. },
  858. _replaceFileInput: function (input) {
  859. var inputClone = input.clone(true);
  860. $('<form></form>').append(inputClone)[0].reset();
  861. // Detaching allows to insert the fileInput on another form
  862. // without loosing the file input value:
  863. input.after(inputClone).detach();
  864. // Avoid memory leaks with the detached file input:
  865. $.cleanData(input.unbind('remove'));
  866. // Replace the original file input element in the fileInput
  867. // elements set with the clone, which has been copied including
  868. // event handlers:
  869. this.options.fileInput = this.options.fileInput.map(function (i, el) {
  870. if (el === input[0]) {
  871. return inputClone[0];
  872. }
  873. return el;
  874. });
  875. // If the widget has been initialized on the file input itself,
  876. // override this.element with the file input clone:
  877. if (input[0] === this.element[0]) {
  878. this.element = inputClone;
  879. }
  880. },
  881. _handleFileTreeEntry: function (entry, path) {
  882. var that = this,
  883. dfd = $.Deferred(),
  884. errorHandler = function (e) {
  885. if (e && !e.entry) {
  886. e.entry = entry;
  887. }
  888. // Since $.when returns immediately if one
  889. // Deferred is rejected, we use resolve instead.
  890. // This allows valid files and invalid items
  891. // to be returned together in one set:
  892. dfd.resolve([e]);
  893. },
  894. dirReader;
  895. path = path || '';
  896. if (entry.isFile) {
  897. if (entry._file) {
  898. // Workaround for Chrome bug #149735
  899. entry._file.relativePath = path;
  900. dfd.resolve(entry._file);
  901. } else {
  902. entry.file(function (file) {
  903. file.relativePath = path;
  904. dfd.resolve(file);
  905. }, errorHandler);
  906. }
  907. } else if (entry.isDirectory) {
  908. dirReader = entry.createReader();
  909. dirReader.readEntries(function (entries) {
  910. that._handleFileTreeEntries(
  911. entries,
  912. path + entry.name + '/'
  913. ).done(function (files) {
  914. dfd.resolve(files);
  915. }).fail(errorHandler);
  916. }, errorHandler);
  917. } else {
  918. // Return an empy list for file system items
  919. // other than files or directories:
  920. dfd.resolve([]);
  921. }
  922. return dfd.promise();
  923. },
  924. _handleFileTreeEntries: function (entries, path) {
  925. var that = this;
  926. return $.when.apply(
  927. $,
  928. $.map(entries, function (entry) {
  929. return that._handleFileTreeEntry(entry, path);
  930. })
  931. ).pipe(function () {
  932. return Array.prototype.concat.apply(
  933. [],
  934. arguments
  935. );
  936. });
  937. },
  938. _getDroppedFiles: function (dataTransfer) {
  939. dataTransfer = dataTransfer || {};
  940. var items = dataTransfer.items;
  941. if (items && items.length && (items[0].webkitGetAsEntry ||
  942. items[0].getAsEntry)) {
  943. return this._handleFileTreeEntries(
  944. $.map(items, function (item) {
  945. var entry;
  946. if (item.webkitGetAsEntry) {
  947. entry = item.webkitGetAsEntry();
  948. if (entry) {
  949. // Workaround for Chrome bug #149735:
  950. entry._file = item.getAsFile();
  951. }
  952. return entry;
  953. }
  954. return item.getAsEntry();
  955. })
  956. );
  957. }
  958. return $.Deferred().resolve(
  959. $.makeArray(dataTransfer.files)
  960. ).promise();
  961. },
  962. _getSingleFileInputFiles: function (fileInput) {
  963. fileInput = $(fileInput);
  964. var entries = fileInput.prop('webkitEntries') ||
  965. fileInput.prop('entries'),
  966. files,
  967. value;
  968. if (entries && entries.length) {
  969. return this._handleFileTreeEntries(entries);
  970. }
  971. files = $.makeArray(fileInput.prop('files'));
  972. if (!files.length) {
  973. value = fileInput.prop('value');
  974. if (!value) {
  975. return $.Deferred().resolve([]).promise();
  976. }
  977. // If the files property is not available, the browser does not
  978. // support the File API and we add a pseudo File object with
  979. // the input value as name with path information removed:
  980. files = [{name: value.replace(/^.*\\/, '')}];
  981. } else if (files[0].name === undefined && files[0].fileName) {
  982. // File normalization for Safari 4 and Firefox 3:
  983. $.each(files, function (index, file) {
  984. file.name = file.fileName;
  985. file.size = file.fileSize;
  986. });
  987. }
  988. return $.Deferred().resolve(files).promise();
  989. },
  990. _getFileInputFiles: function (fileInput) {
  991. if (!(fileInput instanceof $) || fileInput.length === 1) {
  992. return this._getSingleFileInputFiles(fileInput);
  993. }
  994. return $.when.apply(
  995. $,
  996. $.map(fileInput, this._getSingleFileInputFiles)
  997. ).pipe(function () {
  998. return Array.prototype.concat.apply(
  999. [],
  1000. arguments
  1001. );
  1002. });
  1003. },
  1004. _onChange: function (e) {
  1005. var that = this,
  1006. data = {
  1007. fileInput: $(e.target),
  1008. form: $(e.target.form)
  1009. };
  1010. this._getFileInputFiles(data.fileInput).always(function (files) {
  1011. data.files = files;
  1012. if (that.options.replaceFileInput) {
  1013. that._replaceFileInput(data.fileInput);
  1014. }
  1015. if (that._trigger('change', e, data) !== false) {
  1016. that._onAdd(e, data);
  1017. }
  1018. });
  1019. },
  1020. _onPaste: function (e) {
  1021. var items = e.originalEvent && e.originalEvent.clipboardData &&
  1022. e.originalEvent.clipboardData.items,
  1023. data = {files: []};
  1024. if (items && items.length) {
  1025. $.each(items, function (index, item) {
  1026. var file = item.getAsFile && item.getAsFile();
  1027. if (file) {
  1028. data.files.push(file);
  1029. }
  1030. });
  1031. if (this._trigger('paste', e, data) === false ||
  1032. this._onAdd(e, data) === false) {
  1033. return false;
  1034. }
  1035. }
  1036. },
  1037. _onDrop: function (e) {
  1038. var that = this,
  1039. dataTransfer = e.dataTransfer = e.originalEvent &&
  1040. e.originalEvent.dataTransfer,
  1041. data = {};
  1042. if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
  1043. e.preventDefault();
  1044. this._getDroppedFiles(dataTransfer).always(function (files) {
  1045. data.files = files;
  1046. if (that._trigger('drop', e, data) !== false) {
  1047. that._onAdd(e, data);
  1048. }
  1049. });
  1050. }
  1051. },
  1052. _onDragOver: function (e) {
  1053. var dataTransfer = e.dataTransfer = e.originalEvent &&
  1054. e.originalEvent.dataTransfer;
  1055. if (dataTransfer) {
  1056. if (this._trigger('dragover', e) === false) {
  1057. return false;
  1058. }
  1059. if ($.inArray('Files', dataTransfer.types) !== -1) {
  1060. dataTransfer.dropEffect = 'copy';
  1061. e.preventDefault();
  1062. }
  1063. }
  1064. },
  1065. _initEventHandlers: function () {
  1066. if (this._isXHRUpload(this.options)) {
  1067. this._on(this.options.dropZone, {
  1068. dragover: this._onDragOver,
  1069. drop: this._onDrop
  1070. });
  1071. this._on(this.options.pasteZone, {
  1072. paste: this._onPaste
  1073. });
  1074. }
  1075. this._on(this.options.fileInput, {
  1076. change: this._onChange
  1077. });
  1078. },
  1079. _destroyEventHandlers: function () {
  1080. this._off(this.options.dropZone, 'dragover drop');
  1081. this._off(this.options.pasteZone, 'paste');
  1082. this._off(this.options.fileInput, 'change');
  1083. },
  1084. _setOption: function (key, value) {
  1085. var reinit = $.inArray(key, this._specialOptions) !== -1;
  1086. if (reinit) {
  1087. this._destroyEventHandlers();
  1088. }
  1089. this._super(key, value);
  1090. if (reinit) {
  1091. this._initSpecialOptions();
  1092. this._initEventHandlers();
  1093. }
  1094. },
  1095. _initSpecialOptions: function () {
  1096. var options = this.options;
  1097. if (options.fileInput === undefined) {
  1098. options.fileInput = this.element.is('input[type="file"]') ?
  1099. this.element : this.element.find('input[type="file"]');
  1100. } else if (!(options.fileInput instanceof $)) {
  1101. options.fileInput = $(options.fileInput);
  1102. }
  1103. if (!(options.dropZone instanceof $)) {
  1104. options.dropZone = $(options.dropZone);
  1105. }
  1106. if (!(options.pasteZone instanceof $)) {
  1107. options.pasteZone = $(options.pasteZone);
  1108. }
  1109. },
  1110. _getRegExp: function (str) {
  1111. var parts = str.split('/'),
  1112. modifiers = parts.pop();
  1113. parts.shift();
  1114. return new RegExp(parts.join('/'), modifiers);
  1115. },
  1116. _isRegExpOption: function (key, value) {
  1117. return key !== 'url' && $.type(value) === 'string' &&
  1118. /^\/.*\/[igm]{0,3}$/.test(value);
  1119. },
  1120. _initDataAttributes: function () {
  1121. var that = this,
  1122. options = this.options;
  1123. // Initialize options set via HTML5 data-attributes:
  1124. $.each(
  1125. $(this.element[0].cloneNode(false)).data(),
  1126. function (key, value) {
  1127. if (that._isRegExpOption(key, value)) {
  1128. value = that._getRegExp(value);
  1129. }
  1130. options[key] = value;
  1131. }
  1132. );
  1133. },
  1134. _create: function () {
  1135. this._initDataAttributes();
  1136. this._initSpecialOptions();
  1137. this._slots = [];
  1138. this._sequence = this._getXHRPromise(true);
  1139. this._sending = this._active = 0;
  1140. this._initProgressObject(this);
  1141. this._initEventHandlers();
  1142. },
  1143. // This method is exposed to the widget API and allows to query
  1144. // the number of active uploads:
  1145. active: function () {
  1146. return this._active;
  1147. },
  1148. // This method is exposed to the widget API and allows to query
  1149. // the widget upload progress.
  1150. // It returns an object with loaded, total and bitrate properties
  1151. // for the running uploads:
  1152. progress: function () {
  1153. return this._progress;
  1154. },
  1155. // This method is exposed to the widget API and allows adding files
  1156. // using the fileupload API. The data parameter accepts an object which
  1157. // must have a files property and can contain additional options:
  1158. // .fileupload('add', {files: filesList});
  1159. add: function (data) {
  1160. var that = this;
  1161. if (!data || this.options.disabled) {
  1162. return;
  1163. }
  1164. if (data.fileInput && !data.files) {
  1165. this._getFileInputFiles(data.fileInput).always(function (files) {
  1166. data.files = files;
  1167. that._onAdd(null, data);
  1168. });
  1169. } else {
  1170. data.files = $.makeArray(data.files);
  1171. this._onAdd(null, data);
  1172. }
  1173. },
  1174. // This method is exposed to the widget API and allows sending files
  1175. // using the fileupload API. The data parameter accepts an object which
  1176. // must have a files or fileInput property and can contain additional options:
  1177. // .fileupload('send', {files: filesList});
  1178. // The method returns a Promise object for the file upload call.
  1179. send: function (data) {
  1180. if (data && !this.options.disabled) {
  1181. if (data.fileInput && !data.files) {
  1182. var that = this,
  1183. dfd = $.Deferred(),
  1184. promise = dfd.promise(),
  1185. jqXHR,
  1186. aborted;
  1187. promise.abort = function () {
  1188. aborted = true;
  1189. if (jqXHR) {
  1190. return jqXHR.abort();
  1191. }
  1192. dfd.reject(null, 'abort', 'abort');
  1193. return promise;
  1194. };
  1195. this._getFileInputFiles(data.fileInput).always(
  1196. function (files) {
  1197. if (aborted) {
  1198. return;
  1199. }
  1200. data.files = files;
  1201. jqXHR = that._onSend(null, data).then(
  1202. function (result, textStatus, jqXHR) {
  1203. dfd.resolve(result, textStatus, jqXHR);
  1204. },
  1205. function (jqXHR, textStatus, errorThrown) {
  1206. dfd.reject(jqXHR, textStatus, errorThrown);
  1207. }
  1208. );
  1209. }
  1210. );
  1211. return this._enhancePromise(promise);
  1212. }
  1213. data.files = $.makeArray(data.files);
  1214. if (data.files.length) {
  1215. return this._onSend(null, data);
  1216. }
  1217. }
  1218. return this._getXHRPromise(false, data && data.context);
  1219. }
  1220. });
  1221. }));