jquery.fileupload.js 62 KB

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