jquery.fileupload.js 63 KB

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