jquery.fileupload.js 55 KB

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