You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jquery.fileupload.js 63KB

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