OnlyOffice在线文档

jquery.fileupload.js 49KB

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