Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

1607 righe
55 KiB

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