jquery.fileupload.js 63 KB

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