jquery.fileupload.js 51 KB

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