jquery.fileupload.js 63 KB

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