jquery.fileupload.local.js 60 KB

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