jquery.fileupload.js 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  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])).then(
  604. function () {
  605. if (data.errorThrown) {
  606. return $.Deferred()
  607. .rejectWith(that, [data]).promise();
  608. }
  609. return getPromise(arguments);
  610. }
  611. ).then(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.then(send);
  890. } else {
  891. this._sequence = this._sequence.then(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. entries = [],
  1022. dirReader,
  1023. errorHandler = function (e) {
  1024. if (e && !e.entry) {
  1025. e.entry = entry;
  1026. }
  1027. // Since $.when returns immediately if one
  1028. // Deferred is rejected, we use resolve instead.
  1029. // This allows valid files and invalid items
  1030. // to be returned together in one set:
  1031. dfd.resolve([e]);
  1032. },
  1033. successHandler = function (entries) {
  1034. that._handleFileTreeEntries(
  1035. entries,
  1036. path + entry.name + '/'
  1037. ).done(function (files) {
  1038. dfd.resolve(files);
  1039. }).fail(errorHandler);
  1040. },
  1041. readEntries = function () {
  1042. dirReader.readEntries(function (results) {
  1043. if (!results.length) {
  1044. successHandler(entries);
  1045. } else {
  1046. entries = entries.concat(results);
  1047. readEntries();
  1048. }
  1049. }, errorHandler);
  1050. };
  1051. path = path || '';
  1052. if (entry.isFile) {
  1053. if (entry._file) {
  1054. // Workaround for Chrome bug #149735
  1055. entry._file.relativePath = path;
  1056. dfd.resolve(entry._file);
  1057. } else {
  1058. entry.file(function (file) {
  1059. file.relativePath = path;
  1060. dfd.resolve(file);
  1061. }, errorHandler);
  1062. }
  1063. } else if (entry.isDirectory) {
  1064. dirReader = entry.createReader();
  1065. readEntries();
  1066. } else {
  1067. // Return an empy list for file system items
  1068. // other than files or directories:
  1069. dfd.resolve([]);
  1070. }
  1071. return dfd.promise();
  1072. },
  1073. _handleFileTreeEntries: function (entries, path) {
  1074. var that = this;
  1075. return $.when.apply(
  1076. $,
  1077. $.map(entries, function (entry) {
  1078. return that._handleFileTreeEntry(entry, path);
  1079. })
  1080. ).then(function () {
  1081. return Array.prototype.concat.apply(
  1082. [],
  1083. arguments
  1084. );
  1085. });
  1086. },
  1087. _getDroppedFiles: function (dataTransfer) {
  1088. dataTransfer = dataTransfer || {};
  1089. var items = dataTransfer.items;
  1090. if (items && items.length && (items[0].webkitGetAsEntry ||
  1091. items[0].getAsEntry)) {
  1092. return this._handleFileTreeEntries(
  1093. $.map(items, function (item) {
  1094. var entry;
  1095. if (item.webkitGetAsEntry) {
  1096. entry = item.webkitGetAsEntry();
  1097. if (entry) {
  1098. // Workaround for Chrome bug #149735:
  1099. entry._file = item.getAsFile();
  1100. }
  1101. return entry;
  1102. }
  1103. return item.getAsEntry();
  1104. })
  1105. );
  1106. }
  1107. return $.Deferred().resolve(
  1108. $.makeArray(dataTransfer.files)
  1109. ).promise();
  1110. },
  1111. _getSingleFileInputFiles: function (fileInput) {
  1112. fileInput = $(fileInput);
  1113. var entries = fileInput.prop('webkitEntries') ||
  1114. fileInput.prop('entries'),
  1115. files,
  1116. value;
  1117. if (entries && entries.length) {
  1118. return this._handleFileTreeEntries(entries);
  1119. }
  1120. files = $.makeArray(fileInput.prop('files'));
  1121. if (!files.length) {
  1122. value = fileInput.prop('value');
  1123. if (!value) {
  1124. return $.Deferred().resolve([]).promise();
  1125. }
  1126. // If the files property is not available, the browser does not
  1127. // support the File API and we add a pseudo File object with
  1128. // the input value as name with path information removed:
  1129. files = [{name: value.replace(/^.*\\/, '')}];
  1130. } else if (files[0].name === undefined && files[0].fileName) {
  1131. // File normalization for Safari 4 and Firefox 3:
  1132. $.each(files, function (index, file) {
  1133. file.name = file.fileName;
  1134. file.size = file.fileSize;
  1135. });
  1136. }
  1137. return $.Deferred().resolve(files).promise();
  1138. },
  1139. _getFileInputFiles: function (fileInput) {
  1140. if (!(fileInput instanceof $) || fileInput.length === 1) {
  1141. return this._getSingleFileInputFiles(fileInput);
  1142. }
  1143. return $.when.apply(
  1144. $,
  1145. $.map(fileInput, this._getSingleFileInputFiles)
  1146. ).then(function () {
  1147. return Array.prototype.concat.apply(
  1148. [],
  1149. arguments
  1150. );
  1151. });
  1152. },
  1153. _onChange: function (e) {
  1154. var that = this,
  1155. data = {
  1156. fileInput: $(e.target),
  1157. form: $(e.target.form)
  1158. };
  1159. this._getFileInputFiles(data.fileInput).always(function (files) {
  1160. data.files = files;
  1161. if (that.options.replaceFileInput) {
  1162. that._replaceFileInput(data);
  1163. }
  1164. if (that._trigger(
  1165. 'change',
  1166. $.Event('change', {delegatedEvent: e}),
  1167. data
  1168. ) !== false) {
  1169. that._onAdd(e, data);
  1170. }
  1171. });
  1172. },
  1173. _onPaste: function (e) {
  1174. var items = e.originalEvent && e.originalEvent.clipboardData &&
  1175. e.originalEvent.clipboardData.items,
  1176. data = {files: []};
  1177. if (items && items.length) {
  1178. $.each(items, function (index, item) {
  1179. var file = item.getAsFile && item.getAsFile();
  1180. if (file) {
  1181. data.files.push(file);
  1182. }
  1183. });
  1184. if (this._trigger(
  1185. 'paste',
  1186. $.Event('paste', {delegatedEvent: e}),
  1187. data
  1188. ) !== false) {
  1189. this._onAdd(e, data);
  1190. }
  1191. }
  1192. },
  1193. _onDrop: function (e) {
  1194. e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
  1195. var that = this,
  1196. dataTransfer = e.dataTransfer,
  1197. data = {};
  1198. if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
  1199. e.preventDefault();
  1200. this._getDroppedFiles(dataTransfer).always(function (files) {
  1201. data.files = files;
  1202. if (that._trigger(
  1203. 'drop',
  1204. $.Event('drop', {delegatedEvent: e}),
  1205. data
  1206. ) !== false) {
  1207. that._onAdd(e, data);
  1208. }
  1209. });
  1210. }
  1211. },
  1212. _onDragOver: getDragHandler('dragover'),
  1213. _onDragEnter: getDragHandler('dragenter'),
  1214. _onDragLeave: getDragHandler('dragleave'),
  1215. _initEventHandlers: function () {
  1216. if (this._isXHRUpload(this.options)) {
  1217. this._on(this.options.dropZone, {
  1218. dragover: this._onDragOver,
  1219. drop: this._onDrop,
  1220. // event.preventDefault() on dragenter is required for IE10+:
  1221. dragenter: this._onDragEnter,
  1222. // dragleave is not required, but added for completeness:
  1223. dragleave: this._onDragLeave
  1224. });
  1225. this._on(this.options.pasteZone, {
  1226. paste: this._onPaste
  1227. });
  1228. }
  1229. if ($.support.fileInput) {
  1230. this._on(this.options.fileInput, {
  1231. change: this._onChange
  1232. });
  1233. }
  1234. },
  1235. _destroyEventHandlers: function () {
  1236. this._off(this.options.dropZone, 'dragenter dragleave dragover drop');
  1237. this._off(this.options.pasteZone, 'paste');
  1238. this._off(this.options.fileInput, 'change');
  1239. },
  1240. _destroy: function () {
  1241. this._destroyEventHandlers();
  1242. },
  1243. _setOption: function (key, value) {
  1244. var reinit = $.inArray(key, this._specialOptions) !== -1;
  1245. if (reinit) {
  1246. this._destroyEventHandlers();
  1247. }
  1248. this._super(key, value);
  1249. if (reinit) {
  1250. this._initSpecialOptions();
  1251. this._initEventHandlers();
  1252. }
  1253. },
  1254. _initSpecialOptions: function () {
  1255. var options = this.options;
  1256. if (options.fileInput === undefined) {
  1257. options.fileInput = this.element.is('input[type="file"]') ?
  1258. this.element : this.element.find('input[type="file"]');
  1259. } else if (!(options.fileInput instanceof $)) {
  1260. options.fileInput = $(options.fileInput);
  1261. }
  1262. if (!(options.dropZone instanceof $)) {
  1263. options.dropZone = $(options.dropZone);
  1264. }
  1265. if (!(options.pasteZone instanceof $)) {
  1266. options.pasteZone = $(options.pasteZone);
  1267. }
  1268. },
  1269. _getRegExp: function (str) {
  1270. var parts = str.split('/'),
  1271. modifiers = parts.pop();
  1272. parts.shift();
  1273. return new RegExp(parts.join('/'), modifiers);
  1274. },
  1275. _isRegExpOption: function (key, value) {
  1276. return key !== 'url' && $.type(value) === 'string' &&
  1277. /^\/.*\/[igm]{0,3}$/.test(value);
  1278. },
  1279. _initDataAttributes: function () {
  1280. var that = this,
  1281. options = this.options,
  1282. data = this.element.data();
  1283. // Initialize options set via HTML5 data-attributes:
  1284. $.each(
  1285. this.element[0].attributes,
  1286. function (index, attr) {
  1287. var key = attr.name.toLowerCase(),
  1288. value;
  1289. if (/^data-/.test(key)) {
  1290. // Convert hyphen-ated key to camelCase:
  1291. key = key.slice(5).replace(/-[a-z]/g, function (str) {
  1292. return str.charAt(1).toUpperCase();
  1293. });
  1294. value = data[key];
  1295. if (that._isRegExpOption(key, value)) {
  1296. value = that._getRegExp(value);
  1297. }
  1298. options[key] = value;
  1299. }
  1300. }
  1301. );
  1302. },
  1303. _create: function () {
  1304. this._initDataAttributes();
  1305. this._initSpecialOptions();
  1306. this._slots = [];
  1307. this._sequence = this._getXHRPromise(true);
  1308. this._sending = this._active = 0;
  1309. this._initProgressObject(this);
  1310. this._initEventHandlers();
  1311. },
  1312. // This method is exposed to the widget API and allows to query
  1313. // the number of active uploads:
  1314. active: function () {
  1315. return this._active;
  1316. },
  1317. // This method is exposed to the widget API and allows to query
  1318. // the widget upload progress.
  1319. // It returns an object with loaded, total and bitrate properties
  1320. // for the running uploads:
  1321. progress: function () {
  1322. return this._progress;
  1323. },
  1324. // This method is exposed to the widget API and allows adding files
  1325. // using the fileupload API. The data parameter accepts an object which
  1326. // must have a files property and can contain additional options:
  1327. // .fileupload('add', {files: filesList});
  1328. add: function (data) {
  1329. var that = this;
  1330. if (!data || this.options.disabled) {
  1331. return;
  1332. }
  1333. if (data.fileInput && !data.files) {
  1334. this._getFileInputFiles(data.fileInput).always(function (files) {
  1335. data.files = files;
  1336. that._onAdd(null, data);
  1337. });
  1338. } else {
  1339. data.files = $.makeArray(data.files);
  1340. this._onAdd(null, data);
  1341. }
  1342. },
  1343. // This method is exposed to the widget API and allows sending files
  1344. // using the fileupload API. The data parameter accepts an object which
  1345. // must have a files or fileInput property and can contain additional options:
  1346. // .fileupload('send', {files: filesList});
  1347. // The method returns a Promise object for the file upload call.
  1348. send: function (data) {
  1349. if (data && !this.options.disabled) {
  1350. if (data.fileInput && !data.files) {
  1351. var that = this,
  1352. dfd = $.Deferred(),
  1353. promise = dfd.promise(),
  1354. jqXHR,
  1355. aborted;
  1356. promise.abort = function () {
  1357. aborted = true;
  1358. if (jqXHR) {
  1359. return jqXHR.abort();
  1360. }
  1361. dfd.reject(null, 'abort', 'abort');
  1362. return promise;
  1363. };
  1364. this._getFileInputFiles(data.fileInput).always(
  1365. function (files) {
  1366. if (aborted) {
  1367. return;
  1368. }
  1369. if (!files.length) {
  1370. dfd.reject();
  1371. return;
  1372. }
  1373. data.files = files;
  1374. jqXHR = that._onSend(null, data);
  1375. jqXHR.then(
  1376. function (result, textStatus, jqXHR) {
  1377. dfd.resolve(result, textStatus, jqXHR);
  1378. },
  1379. function (jqXHR, textStatus, errorThrown) {
  1380. dfd.reject(jqXHR, textStatus, errorThrown);
  1381. }
  1382. );
  1383. }
  1384. );
  1385. return this._enhancePromise(promise);
  1386. }
  1387. data.files = $.makeArray(data.files);
  1388. if (data.files.length) {
  1389. return this._onSend(null, data);
  1390. }
  1391. }
  1392. return this._getXHRPromise(false, data && data.context);
  1393. }
  1394. });
  1395. }));