1
0

jquery.fileupload.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  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. // Dynamically adjust the chunk size for Chunking V2 to fit into the 10000 chunk limit
  682. if (file.size/mcs > 10000) {
  683. mcs = Math.ceil(file.size/10000)
  684. }
  685. if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
  686. options.data) {
  687. return false;
  688. }
  689. if (testOnly) {
  690. return true;
  691. }
  692. if (ub >= fs) {
  693. file.error = options.i18n('uploadedBytes');
  694. return this._getXHRPromise(
  695. false,
  696. options.context,
  697. [null, 'error', file.error]
  698. );
  699. }
  700. // The chunk upload method:
  701. upload = function () {
  702. // Clone the options object for each chunk upload:
  703. var o = $.extend({}, options),
  704. currentLoaded = o._progress.loaded;
  705. o.blob = slice.call(
  706. file,
  707. ub,
  708. ub + mcs,
  709. file.type
  710. );
  711. // Store the current chunk size, as the blob itself
  712. // will be dereferenced after data processing:
  713. o.chunkSize = o.blob.size;
  714. // Expose the chunk bytes position range:
  715. o.contentRange = 'bytes ' + ub + '-' +
  716. (ub + o.chunkSize - 1) + '/' + fs;
  717. // Process the upload data (the blob and potential form data):
  718. that._initXHRData(o);
  719. // Add progress listeners for this chunk upload:
  720. that._initProgressListener(o);
  721. jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
  722. that._getXHRPromise(false, o.context))
  723. .done(function (result, textStatus, jqXHR) {
  724. ub = that._getUploadedBytes(jqXHR) ||
  725. (ub + o.chunkSize);
  726. // Create a progress event if no final progress event
  727. // with loaded equaling total has been triggered
  728. // for this chunk:
  729. if (currentLoaded + o.chunkSize - o._progress.loaded) {
  730. that._onProgress($.Event('progress', {
  731. lengthComputable: true,
  732. loaded: ub - o.uploadedBytes,
  733. total: ub - o.uploadedBytes
  734. }), o);
  735. }
  736. options.uploadedBytes = o.uploadedBytes = ub;
  737. o.result = result;
  738. o.textStatus = textStatus;
  739. o.jqXHR = jqXHR;
  740. that._trigger('chunkdone', null, o);
  741. that._trigger('chunkalways', null, o);
  742. if (ub < fs) {
  743. // File upload not yet complete,
  744. // continue with the next chunk:
  745. upload();
  746. } else {
  747. dfd.resolveWith(
  748. o.context,
  749. [result, textStatus, jqXHR]
  750. );
  751. }
  752. })
  753. .fail(function (jqXHR, textStatus, errorThrown) {
  754. o.jqXHR = jqXHR;
  755. o.textStatus = textStatus;
  756. o.errorThrown = errorThrown;
  757. that._trigger('chunkfail', null, o);
  758. that._trigger('chunkalways', null, o);
  759. dfd.rejectWith(
  760. o.context,
  761. [jqXHR, textStatus, errorThrown]
  762. );
  763. });
  764. };
  765. this._enhancePromise(promise);
  766. promise.abort = function () {
  767. return jqXHR.abort();
  768. };
  769. upload();
  770. return promise;
  771. },
  772. _beforeSend: function (e, data) {
  773. if (this._active === 0) {
  774. // the start callback is triggered when an upload starts
  775. // and no other uploads are currently running,
  776. // equivalent to the global ajaxStart event:
  777. this._trigger('start');
  778. // Set timer for global bitrate progress calculation:
  779. this._bitrateTimer = new this._BitrateTimer();
  780. // Reset the global progress values:
  781. this._progress.loaded = this._progress.total = 0;
  782. this._progress.bitrate = 0;
  783. }
  784. // Make sure the container objects for the .response() and
  785. // .progress() methods on the data object are available
  786. // and reset to their initial state:
  787. this._initResponseObject(data);
  788. this._initProgressObject(data);
  789. data._progress.loaded = data.loaded = data.uploadedBytes || 0;
  790. data._progress.total = data.total = this._getTotal(data.files) || 1;
  791. data._progress.bitrate = data.bitrate = 0;
  792. this._active += 1;
  793. // Initialize the global progress values:
  794. this._progress.loaded += data.loaded;
  795. this._progress.total += data.total;
  796. },
  797. _onDone: function (result, textStatus, jqXHR, options) {
  798. var total = options._progress.total,
  799. response = options._response;
  800. if (options._progress.loaded < total) {
  801. // Create a progress event if no final progress event
  802. // with loaded equaling total has been triggered:
  803. this._onProgress($.Event('progress', {
  804. lengthComputable: true,
  805. loaded: total,
  806. total: total
  807. }), options);
  808. }
  809. response.result = options.result = result;
  810. response.textStatus = options.textStatus = textStatus;
  811. response.jqXHR = options.jqXHR = jqXHR;
  812. this._trigger('done', null, options);
  813. },
  814. _onFail: function (jqXHR, textStatus, errorThrown, options) {
  815. var response = options._response;
  816. if (options.recalculateProgress) {
  817. // Remove the failed (error or abort) file upload from
  818. // the global progress calculation:
  819. this._progress.loaded -= options._progress.loaded;
  820. this._progress.total -= options._progress.total;
  821. }
  822. response.jqXHR = options.jqXHR = jqXHR;
  823. response.textStatus = options.textStatus = textStatus;
  824. response.errorThrown = options.errorThrown = errorThrown;
  825. this._trigger('fail', null, options);
  826. },
  827. _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
  828. // jqXHRorResult, textStatus and jqXHRorError are added to the
  829. // options object via done and fail callbacks
  830. this._trigger('always', null, options);
  831. },
  832. _onSend: function (e, data) {
  833. if (!data.submit) {
  834. this._addConvenienceMethods(e, data);
  835. }
  836. var that = this,
  837. jqXHR,
  838. aborted,
  839. slot,
  840. pipe,
  841. options = that._getAJAXSettings(data),
  842. send = function () {
  843. that._sending += 1;
  844. // Set timer for bitrate progress calculation:
  845. options._bitrateTimer = new that._BitrateTimer();
  846. jqXHR = jqXHR || (
  847. ((aborted || that._trigger(
  848. 'send',
  849. $.Event('send', {delegatedEvent: e}),
  850. options
  851. ) === false) &&
  852. that._getXHRPromise(false, options.context, aborted)) ||
  853. that._chunkedUpload(options) || $.ajax(options)
  854. ).done(function (result, textStatus, jqXHR) {
  855. that._onDone(result, textStatus, jqXHR, options);
  856. }).fail(function (jqXHR, textStatus, errorThrown) {
  857. that._onFail(jqXHR, textStatus, errorThrown, options);
  858. }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
  859. that._onAlways(
  860. jqXHRorResult,
  861. textStatus,
  862. jqXHRorError,
  863. options
  864. );
  865. that._sending -= 1;
  866. that._active -= 1;
  867. if (options.limitConcurrentUploads &&
  868. options.limitConcurrentUploads > that._sending) {
  869. // Start the next queued upload,
  870. // that has not been aborted:
  871. var nextSlot = that._slots.shift();
  872. while (nextSlot) {
  873. if (that._getDeferredState(nextSlot) === 'pending') {
  874. nextSlot.resolve();
  875. break;
  876. }
  877. nextSlot = that._slots.shift();
  878. }
  879. }
  880. if (that._active === 0) {
  881. // The stop callback is triggered when all uploads have
  882. // been completed, equivalent to the global ajaxStop event:
  883. that._trigger('stop');
  884. }
  885. });
  886. return jqXHR;
  887. };
  888. this._beforeSend(e, options);
  889. if (this.options.sequentialUploads ||
  890. (this.options.limitConcurrentUploads &&
  891. this.options.limitConcurrentUploads <= this._sending)) {
  892. if (this.options.limitConcurrentUploads > 1) {
  893. slot = $.Deferred();
  894. this._slots.push(slot);
  895. pipe = slot.then(send);
  896. } else {
  897. this._sequence = this._sequence.then(send, send);
  898. pipe = this._sequence;
  899. }
  900. // Return the piped Promise object, enhanced with an abort method,
  901. // which is delegated to the jqXHR object of the current upload,
  902. // and jqXHR callbacks mapped to the equivalent Promise methods:
  903. pipe.abort = function () {
  904. aborted = [undefined, 'abort', 'abort'];
  905. if (!jqXHR) {
  906. if (slot) {
  907. slot.rejectWith(options.context, aborted);
  908. }
  909. return send();
  910. }
  911. return jqXHR.abort();
  912. };
  913. return this._enhancePromise(pipe);
  914. }
  915. return send();
  916. },
  917. _onAdd: function (e, data) {
  918. var that = this,
  919. result = true,
  920. options = $.extend({}, this.options, data),
  921. files = data.files,
  922. filesLength = files.length,
  923. limit = options.limitMultiFileUploads,
  924. limitSize = options.limitMultiFileUploadSize,
  925. overhead = options.limitMultiFileUploadSizeOverhead,
  926. batchSize = 0,
  927. paramName = this._getParamName(options),
  928. paramNameSet,
  929. paramNameSlice,
  930. fileSet,
  931. i,
  932. j = 0;
  933. if (!filesLength) {
  934. return false;
  935. }
  936. if (limitSize && files[0].size === undefined) {
  937. limitSize = undefined;
  938. }
  939. if (!(options.singleFileUploads || limit || limitSize) ||
  940. !this._isXHRUpload(options)) {
  941. fileSet = [files];
  942. paramNameSet = [paramName];
  943. } else if (!(options.singleFileUploads || limitSize) && limit) {
  944. fileSet = [];
  945. paramNameSet = [];
  946. for (i = 0; i < filesLength; i += limit) {
  947. fileSet.push(files.slice(i, i + limit));
  948. paramNameSlice = paramName.slice(i, i + limit);
  949. if (!paramNameSlice.length) {
  950. paramNameSlice = paramName;
  951. }
  952. paramNameSet.push(paramNameSlice);
  953. }
  954. } else if (!options.singleFileUploads && limitSize) {
  955. fileSet = [];
  956. paramNameSet = [];
  957. for (i = 0; i < filesLength; i = i + 1) {
  958. batchSize += files[i].size + overhead;
  959. if (i + 1 === filesLength ||
  960. ((batchSize + files[i + 1].size + overhead) > limitSize) ||
  961. (limit && i + 1 - j >= limit)) {
  962. fileSet.push(files.slice(j, i + 1));
  963. paramNameSlice = paramName.slice(j, i + 1);
  964. if (!paramNameSlice.length) {
  965. paramNameSlice = paramName;
  966. }
  967. paramNameSet.push(paramNameSlice);
  968. j = i + 1;
  969. batchSize = 0;
  970. }
  971. }
  972. } else {
  973. paramNameSet = paramName;
  974. }
  975. data.originalFiles = [];
  976. $.each(files, function (file) {
  977. if (!file.isDirectory) {
  978. data.originalFiles.push(file);
  979. }
  980. });
  981. $.each(fileSet || files, function (index, element) {
  982. var newData = $.extend({}, data);
  983. newData.files = fileSet ? element : [element];
  984. newData.paramName = paramNameSet[index];
  985. that._initResponseObject(newData);
  986. that._initProgressObject(newData);
  987. that._addConvenienceMethods(e, newData);
  988. result = that._trigger(
  989. 'add',
  990. $.Event('add', {delegatedEvent: e}),
  991. newData
  992. );
  993. return result;
  994. });
  995. return result;
  996. },
  997. _replaceFileInput: function (data) {
  998. var input = data.fileInput,
  999. inputClone = input.clone(true),
  1000. restoreFocus = input.is(document.activeElement);
  1001. // Add a reference for the new cloned file input to the data argument:
  1002. data.fileInputClone = inputClone;
  1003. $('<form></form>').append(inputClone)[0].reset();
  1004. // Detaching allows to insert the fileInput on another form
  1005. // without losing the file input value:
  1006. input.after(inputClone).detach();
  1007. // If the fileInput had focus before it was detached,
  1008. // restore focus to the inputClone.
  1009. if (restoreFocus) {
  1010. inputClone.focus();
  1011. }
  1012. // Avoid memory leaks with the detached file input:
  1013. $.cleanData(input.unbind('remove'));
  1014. // Replace the original file input element in the fileInput
  1015. // elements set with the clone, which has been copied including
  1016. // event handlers:
  1017. this.options.fileInput = this.options.fileInput.map(function (i, el) {
  1018. if (el === input[0]) {
  1019. return inputClone[0];
  1020. }
  1021. return el;
  1022. });
  1023. // If the widget has been initialized on the file input itself,
  1024. // override this.element with the file input clone:
  1025. if (input[0] === this.element[0]) {
  1026. this.element = inputClone;
  1027. }
  1028. },
  1029. _handleFileTreeEntry: function (entry, path) {
  1030. var that = this,
  1031. dfd = $.Deferred(),
  1032. errorHandler = function (e) {
  1033. if (e && !e.entry) {
  1034. e.entry = entry;
  1035. }
  1036. // Since $.when returns immediately if one
  1037. // Deferred is rejected, we use resolve instead.
  1038. // This allows valid files and invalid items
  1039. // to be returned together in one set:
  1040. dfd.resolve([e]);
  1041. },
  1042. successHandler = function (entries) {
  1043. that._handleFileTreeEntries(
  1044. entries,
  1045. path + entry.name + '/'
  1046. ).done(function (files) {
  1047. // empty folder
  1048. if (!files.length && entry.isDirectory) {
  1049. dfd.resolve(entry);
  1050. } else {
  1051. dfd.resolve(files);
  1052. }
  1053. }).fail(errorHandler);
  1054. },
  1055. readEntries = function () {
  1056. dirReader.readEntries(function (results) {
  1057. if (!results.length) {
  1058. successHandler(entries);
  1059. } else {
  1060. entries = entries.concat(results);
  1061. readEntries();
  1062. }
  1063. }, errorHandler);
  1064. },
  1065. dirReader, entries = [];
  1066. path = path || '';
  1067. if (entry.isFile) {
  1068. if (entry._file) {
  1069. // Workaround for Chrome bug #149735
  1070. entry._file.relativePath = path;
  1071. dfd.resolve(entry._file);
  1072. } else {
  1073. entry.file(function (file) {
  1074. file.relativePath = path;
  1075. dfd.resolve(file);
  1076. }, errorHandler);
  1077. }
  1078. } else if (entry.isDirectory) {
  1079. dirReader = entry.createReader();
  1080. readEntries();
  1081. } else {
  1082. // Return an empty list for file system items
  1083. // other than files or directories:
  1084. dfd.resolve([]);
  1085. }
  1086. return dfd.promise();
  1087. },
  1088. _handleFileTreeEntries: function (entries, path) {
  1089. var that = this;
  1090. return $.when.apply(
  1091. $,
  1092. $.map(entries, function (entry) {
  1093. return that._handleFileTreeEntry(entry, path);
  1094. })
  1095. ).then(function () {
  1096. return Array.prototype.concat.apply(
  1097. [],
  1098. arguments
  1099. );
  1100. });
  1101. },
  1102. _getDroppedFiles: function (dataTransfer) {
  1103. dataTransfer = dataTransfer || {};
  1104. var items = dataTransfer.items;
  1105. if (items && items.length && (items[0].webkitGetAsEntry ||
  1106. items[0].getAsEntry)) {
  1107. return this._handleFileTreeEntries(
  1108. $.map(items, function (item) {
  1109. var entry;
  1110. if (item.webkitGetAsEntry) {
  1111. entry = item.webkitGetAsEntry();
  1112. if (entry) {
  1113. // Workaround for Chrome bug #149735:
  1114. entry._file = item.getAsFile();
  1115. }
  1116. return entry;
  1117. }
  1118. return item.getAsEntry();
  1119. })
  1120. );
  1121. }
  1122. return $.Deferred().resolve(
  1123. $.makeArray(dataTransfer.files)
  1124. ).promise();
  1125. },
  1126. _getSingleFileInputFiles: function (fileInput) {
  1127. fileInput = $(fileInput);
  1128. var entries = fileInput.prop('webkitEntries') ||
  1129. fileInput.prop('entries'),
  1130. files,
  1131. value;
  1132. if (entries && entries.length) {
  1133. return this._handleFileTreeEntries(entries);
  1134. }
  1135. files = $.makeArray(fileInput.prop('files'));
  1136. if (!files.length) {
  1137. value = fileInput.prop('value');
  1138. if (!value) {
  1139. return $.Deferred().resolve([]).promise();
  1140. }
  1141. // If the files property is not available, the browser does not
  1142. // support the File API and we add a pseudo File object with
  1143. // the input value as name with path information removed:
  1144. files = [{name: value.replace(/^.*\\/, '')}];
  1145. } else if (files[0].name === undefined && files[0].fileName) {
  1146. // File normalization for Safari 4 and Firefox 3:
  1147. $.each(files, function (index, file) {
  1148. file.name = file.fileName;
  1149. file.size = file.fileSize;
  1150. });
  1151. }
  1152. return $.Deferred().resolve(files).promise();
  1153. },
  1154. _getFileInputFiles: function (fileInput) {
  1155. if (!(fileInput instanceof $) || fileInput.length === 1) {
  1156. return this._getSingleFileInputFiles(fileInput);
  1157. }
  1158. return $.when.apply(
  1159. $,
  1160. $.map(fileInput, this._getSingleFileInputFiles)
  1161. ).then(function () {
  1162. return Array.prototype.concat.apply(
  1163. [],
  1164. arguments
  1165. );
  1166. });
  1167. },
  1168. _onChange: function (e) {
  1169. var that = this,
  1170. data = {
  1171. fileInput: $(e.target),
  1172. form: $(e.target.form)
  1173. };
  1174. this._getFileInputFiles(data.fileInput).always(function (files) {
  1175. data.files = files;
  1176. if (that.options.replaceFileInput) {
  1177. that._replaceFileInput(data);
  1178. }
  1179. if (that._trigger(
  1180. 'change',
  1181. $.Event('change', {delegatedEvent: e}),
  1182. data
  1183. ) !== false) {
  1184. that._onAdd(e, data);
  1185. }
  1186. });
  1187. },
  1188. _onPaste: function (e) {
  1189. var items = e.originalEvent && e.originalEvent.clipboardData &&
  1190. e.originalEvent.clipboardData.items,
  1191. data = {files: []};
  1192. if (items && items.length) {
  1193. $.each(items, function (index, item) {
  1194. var file = item.getAsFile && item.getAsFile();
  1195. if (file) {
  1196. data.files.push(file);
  1197. }
  1198. });
  1199. if (this._trigger(
  1200. 'paste',
  1201. $.Event('paste', {delegatedEvent: e}),
  1202. data
  1203. ) !== false) {
  1204. this._onAdd(e, data);
  1205. }
  1206. }
  1207. },
  1208. _onDrop: function (e) {
  1209. e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
  1210. var that = this,
  1211. dataTransfer = e.dataTransfer,
  1212. data = {};
  1213. if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
  1214. e.preventDefault();
  1215. this._getDroppedFiles(dataTransfer).always(function (files) {
  1216. data.files = files;
  1217. if (that._trigger(
  1218. 'drop',
  1219. $.Event('drop', {delegatedEvent: e}),
  1220. data
  1221. ) !== false) {
  1222. that._onAdd(e, data);
  1223. }
  1224. });
  1225. } else {
  1226. // "dropnofiles" is triggered to allow proper cleanup of the
  1227. // drag and drop operation, as some browsers trigger "drop"
  1228. // events that have no files even if the "DataTransfer.types" of
  1229. // the "dragover" event included a "Files" item.
  1230. this._trigger(
  1231. 'dropnofiles',
  1232. $.Event('drop', {delegatedEvent: e})
  1233. );
  1234. }
  1235. },
  1236. _onDragOver: getDragHandler('dragover'),
  1237. _onDragEnter: getDragHandler('dragenter'),
  1238. _onDragLeave: getDragHandler('dragleave'),
  1239. _initEventHandlers: function () {
  1240. if (this._isXHRUpload(this.options)) {
  1241. this._on(this.options.dropZone, {
  1242. dragover: this._onDragOver,
  1243. drop: this._onDrop,
  1244. // event.preventDefault() on dragenter is required for IE10+:
  1245. dragenter: this._onDragEnter,
  1246. // dragleave is not required, but added for completeness:
  1247. dragleave: this._onDragLeave
  1248. });
  1249. this._on(this.options.pasteZone, {
  1250. paste: this._onPaste
  1251. });
  1252. }
  1253. if ($.support.fileInput) {
  1254. this._on(this.options.fileInput, {
  1255. change: this._onChange
  1256. });
  1257. }
  1258. },
  1259. _destroyEventHandlers: function () {
  1260. this._off(this.options.dropZone, 'dragenter dragleave dragover drop');
  1261. this._off(this.options.pasteZone, 'paste');
  1262. this._off(this.options.fileInput, 'change');
  1263. },
  1264. _setOption: function (key, value) {
  1265. var reinit = $.inArray(key, this._specialOptions) !== -1;
  1266. if (reinit) {
  1267. this._destroyEventHandlers();
  1268. }
  1269. this._super(key, value);
  1270. if (reinit) {
  1271. this._initSpecialOptions();
  1272. this._initEventHandlers();
  1273. }
  1274. },
  1275. _initSpecialOptions: function () {
  1276. var options = this.options;
  1277. if (options.fileInput === undefined) {
  1278. options.fileInput = this.element.is('input[type="file"]') ?
  1279. this.element : this.element.find('input[type="file"]');
  1280. } else if (!(options.fileInput instanceof $)) {
  1281. options.fileInput = $(options.fileInput);
  1282. }
  1283. if (!(options.dropZone instanceof $)) {
  1284. options.dropZone = $(options.dropZone);
  1285. }
  1286. if (!(options.pasteZone instanceof $)) {
  1287. options.pasteZone = $(options.pasteZone);
  1288. }
  1289. },
  1290. _getRegExp: function (str) {
  1291. var parts = str.split('/'),
  1292. modifiers = parts.pop();
  1293. parts.shift();
  1294. return new RegExp(parts.join('/'), modifiers);
  1295. },
  1296. _isRegExpOption: function (key, value) {
  1297. return key !== 'url' && $.type(value) === 'string' &&
  1298. /^\/.*\/[igm]{0,3}$/.test(value);
  1299. },
  1300. _initDataAttributes: function () {
  1301. var that = this,
  1302. options = this.options,
  1303. data = this.element.data();
  1304. // Initialize options set via HTML5 data-attributes:
  1305. $.each(
  1306. this.element[0].attributes,
  1307. function (index, attr) {
  1308. var key = attr.name.toLowerCase(),
  1309. value;
  1310. if (/^data-/.test(key)) {
  1311. // Convert hyphen-ated key to camelCase:
  1312. key = key.slice(5).replace(/-[a-z]/g, function (str) {
  1313. return str.charAt(1).toUpperCase();
  1314. });
  1315. value = data[key];
  1316. if (that._isRegExpOption(key, value)) {
  1317. value = that._getRegExp(value);
  1318. }
  1319. options[key] = value;
  1320. }
  1321. }
  1322. );
  1323. },
  1324. _create: function () {
  1325. this._initDataAttributes();
  1326. this._initSpecialOptions();
  1327. this._slots = [];
  1328. this._sequence = this._getXHRPromise(true);
  1329. this._sending = this._active = 0;
  1330. this._initProgressObject(this);
  1331. this._initEventHandlers();
  1332. },
  1333. // This method is exposed to the widget API and allows to query
  1334. // the number of active uploads:
  1335. active: function () {
  1336. return this._active;
  1337. },
  1338. // This method is exposed to the widget API and allows to query
  1339. // the widget upload progress.
  1340. // It returns an object with loaded, total and bitrate properties
  1341. // for the running uploads:
  1342. progress: function () {
  1343. return this._progress;
  1344. },
  1345. // This method is exposed to the widget API and allows adding files
  1346. // using the fileupload API. The data parameter accepts an object which
  1347. // must have a files property and can contain additional options:
  1348. // .fileupload('add', {files: filesList});
  1349. add: function (data) {
  1350. var that = this;
  1351. if (!data || this.options.disabled) {
  1352. return;
  1353. }
  1354. if (data.fileInput && !data.files) {
  1355. this._getFileInputFiles(data.fileInput).always(function (files) {
  1356. data.files = files;
  1357. that._onAdd(null, data);
  1358. });
  1359. } else {
  1360. data.files = $.makeArray(data.files);
  1361. this._onAdd(null, data);
  1362. }
  1363. },
  1364. // This method is exposed to the widget API and allows sending files
  1365. // using the fileupload API. The data parameter accepts an object which
  1366. // must have a files or fileInput property and can contain additional options:
  1367. // .fileupload('send', {files: filesList});
  1368. // The method returns a Promise object for the file upload call.
  1369. send: function (data) {
  1370. if (data && !this.options.disabled) {
  1371. if (data.fileInput && !data.files) {
  1372. var that = this,
  1373. dfd = $.Deferred(),
  1374. promise = dfd.promise(),
  1375. jqXHR,
  1376. aborted;
  1377. promise.abort = function () {
  1378. aborted = true;
  1379. if (jqXHR) {
  1380. return jqXHR.abort();
  1381. }
  1382. dfd.reject(null, 'abort', 'abort');
  1383. return promise;
  1384. };
  1385. this._getFileInputFiles(data.fileInput).always(
  1386. function (files) {
  1387. if (aborted) {
  1388. return;
  1389. }
  1390. if (!files.length) {
  1391. dfd.reject();
  1392. return;
  1393. }
  1394. data.files = files;
  1395. jqXHR = that._onSend(null, data);
  1396. jqXHR.then(
  1397. function (result, textStatus, jqXHR) {
  1398. dfd.resolve(result, textStatus, jqXHR);
  1399. },
  1400. function (jqXHR, textStatus, errorThrown) {
  1401. dfd.reject(jqXHR, textStatus, errorThrown);
  1402. }
  1403. );
  1404. }
  1405. );
  1406. return this._enhancePromise(promise);
  1407. }
  1408. data.files = $.makeArray(data.files);
  1409. if (data.files.length) {
  1410. return this._onSend(null, data);
  1411. }
  1412. }
  1413. return this._getXHRPromise(false, data && data.context);
  1414. }
  1415. });
  1416. }));