jquery.fileupload.js 50 KB

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