jquery.fileupload.js 55 KB

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