jquery.fileupload.js 60 KB

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