jquery.fileupload.js 55 KB

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