jquery.fileupload.js 63 KB

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