jquery.fileupload.js 47KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. /*
  2. * jQuery File Upload Plugin 5.19.2
  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, 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. // Additional form data to be sent along with the file uploads can be set
  111. // using this option, which accepts an array of objects with name and
  112. // value properties, a function returning such an array, a FormData
  113. // object (for XHR file uploads), or a simple object.
  114. // The form of the first fileInput is given as parameter to the function:
  115. formData: function (form) {
  116. return form.serializeArray();
  117. },
  118. // The add callback is invoked as soon as files are added to the fileupload
  119. // widget (via file input selection, drag & drop, paste or add API call).
  120. // If the singleFileUploads option is enabled, this callback will be
  121. // called once for each file in the selection for XHR file uplaods, else
  122. // once for each file selection.
  123. // The upload starts when the submit method is invoked on the data parameter.
  124. // The data object contains a files property holding the added files
  125. // and allows to override plugin options as well as define ajax settings.
  126. // Listeners for this callback can also be bound the following way:
  127. // .bind('fileuploadadd', func);
  128. // data.submit() returns a Promise object and allows to attach additional
  129. // handlers using jQuery's Deferred callbacks:
  130. // data.submit().done(func).fail(func).always(func);
  131. add: function (e, data) {
  132. data.submit();
  133. },
  134. // Other callbacks:
  135. // Callback for the submit event of each file upload:
  136. // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
  137. // Callback for the start of each file upload request:
  138. // send: function (e, data) {}, // .bind('fileuploadsend', func);
  139. // Callback for successful uploads:
  140. // done: function (e, data) {}, // .bind('fileuploaddone', func);
  141. // Callback for failed (abort or error) uploads:
  142. // fail: function (e, data) {}, // .bind('fileuploadfail', func);
  143. // Callback for completed (success, abort or error) requests:
  144. // always: function (e, data) {}, // .bind('fileuploadalways', func);
  145. // Callback for upload progress events:
  146. // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
  147. // Callback for global upload progress events:
  148. // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
  149. // Callback for uploads start, equivalent to the global ajaxStart event:
  150. // start: function (e) {}, // .bind('fileuploadstart', func);
  151. // Callback for uploads stop, equivalent to the global ajaxStop event:
  152. // stop: function (e) {}, // .bind('fileuploadstop', func);
  153. // Callback for change events of the fileInput(s):
  154. // change: function (e, data) {}, // .bind('fileuploadchange', func);
  155. // Callback for paste events to the pasteZone(s):
  156. // paste: function (e, data) {}, // .bind('fileuploadpaste', func);
  157. // Callback for drop events of the dropZone(s):
  158. // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
  159. // Callback for dragover events of the dropZone(s):
  160. // dragover: function (e) {}, // .bind('fileuploaddragover', func);
  161. // The plugin options are used as settings object for the ajax calls.
  162. // The following are jQuery ajax settings required for the file uploads:
  163. processData: false,
  164. contentType: false,
  165. cache: false
  166. },
  167. // A list of options that require a refresh after assigning a new value:
  168. _refreshOptionsList: [
  169. 'fileInput',
  170. 'dropZone',
  171. 'pasteZone',
  172. 'multipart',
  173. 'forceIframeTransport'
  174. ],
  175. _BitrateTimer: function () {
  176. this.timestamp = +(new Date());
  177. this.loaded = 0;
  178. this.bitrate = 0;
  179. this.getBitrate = function (now, loaded, interval) {
  180. var timeDiff = now - this.timestamp;
  181. if (!this.bitrate || !interval || timeDiff > interval) {
  182. this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
  183. this.loaded = loaded;
  184. this.timestamp = now;
  185. }
  186. return this.bitrate;
  187. };
  188. },
  189. _isXHRUpload: function (options) {
  190. return !options.forceIframeTransport &&
  191. ((!options.multipart && $.support.xhrFileUpload) ||
  192. $.support.xhrFormDataFileUpload);
  193. },
  194. _getFormData: function (options) {
  195. var formData;
  196. if (typeof options.formData === 'function') {
  197. return options.formData(options.form);
  198. }
  199. if ($.isArray(options.formData)) {
  200. return options.formData;
  201. }
  202. if (options.formData) {
  203. formData = [];
  204. $.each(options.formData, function (name, value) {
  205. formData.push({name: name, value: value});
  206. });
  207. return formData;
  208. }
  209. return [];
  210. },
  211. _getTotal: function (files) {
  212. var total = 0;
  213. $.each(files, function (index, file) {
  214. total += file.size || 1;
  215. });
  216. return total;
  217. },
  218. _onProgress: function (e, data) {
  219. if (e.lengthComputable) {
  220. var now = +(new Date()),
  221. total,
  222. loaded;
  223. if (data._time && data.progressInterval &&
  224. (now - data._time < data.progressInterval) &&
  225. e.loaded !== e.total) {
  226. return;
  227. }
  228. data._time = now;
  229. total = data.total || this._getTotal(data.files);
  230. loaded = parseInt(
  231. e.loaded / e.total * (data.chunkSize || total),
  232. 10
  233. ) + (data.uploadedBytes || 0);
  234. this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
  235. data.lengthComputable = true;
  236. data.loaded = loaded;
  237. data.total = total;
  238. data.bitrate = data._bitrateTimer.getBitrate(
  239. now,
  240. loaded,
  241. data.bitrateInterval
  242. );
  243. // Trigger a custom progress event with a total data property set
  244. // to the file size(s) of the current upload and a loaded data
  245. // property calculated accordingly:
  246. this._trigger('progress', e, data);
  247. // Trigger a global progress event for all current file uploads,
  248. // including ajax calls queued for sequential file uploads:
  249. this._trigger('progressall', e, {
  250. lengthComputable: true,
  251. loaded: this._loaded,
  252. total: this._total,
  253. bitrate: this._bitrateTimer.getBitrate(
  254. now,
  255. this._loaded,
  256. data.bitrateInterval
  257. )
  258. });
  259. }
  260. },
  261. _initProgressListener: function (options) {
  262. var that = this,
  263. xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
  264. // Accesss to the native XHR object is required to add event listeners
  265. // for the upload progress event:
  266. if (xhr.upload) {
  267. $(xhr.upload).bind('progress', function (e) {
  268. var oe = e.originalEvent;
  269. // Make sure the progress event properties get copied over:
  270. e.lengthComputable = oe.lengthComputable;
  271. e.loaded = oe.loaded;
  272. e.total = oe.total;
  273. that._onProgress(e, options);
  274. });
  275. options.xhr = function () {
  276. return xhr;
  277. };
  278. }
  279. },
  280. _initXHRData: function (options) {
  281. var formData,
  282. file = options.files[0],
  283. // Ignore non-multipart setting if not supported:
  284. multipart = options.multipart || !$.support.xhrFileUpload,
  285. paramName = options.paramName[0];
  286. options.headers = options.headers || {};
  287. if (options.contentRange) {
  288. options.headers['Content-Range'] = options.contentRange;
  289. }
  290. if (!multipart) {
  291. options.headers['Content-Disposition'] = 'attachment; filename="' +
  292. encodeURI(file.name) + '"';
  293. options.contentType = file.type;
  294. options.data = options.blob || file;
  295. } else if ($.support.xhrFormDataFileUpload) {
  296. if (options.postMessage) {
  297. // window.postMessage does not allow sending FormData
  298. // objects, so we just add the File/Blob objects to
  299. // the formData array and let the postMessage window
  300. // create the FormData object out of this array:
  301. formData = this._getFormData(options);
  302. if (options.blob) {
  303. formData.push({
  304. name: paramName,
  305. value: options.blob
  306. });
  307. } else {
  308. $.each(options.files, function (index, file) {
  309. formData.push({
  310. name: options.paramName[index] || paramName,
  311. value: file
  312. });
  313. });
  314. }
  315. } else {
  316. if (options.formData instanceof FormData) {
  317. formData = options.formData;
  318. } else {
  319. formData = new FormData();
  320. $.each(this._getFormData(options), function (index, field) {
  321. formData.append(field.name, field.value);
  322. });
  323. }
  324. if (options.blob) {
  325. options.headers['Content-Disposition'] = 'attachment; filename="' +
  326. encodeURI(file.name) + '"';
  327. options.headers['Content-Description'] = encodeURI(file.type);
  328. formData.append(paramName, options.blob, file.name);
  329. } else {
  330. $.each(options.files, function (index, file) {
  331. // File objects are also Blob instances.
  332. // This check allows the tests to run with
  333. // dummy objects:
  334. if (file instanceof Blob) {
  335. formData.append(
  336. options.paramName[index] || paramName,
  337. file,
  338. file.name
  339. );
  340. }
  341. });
  342. }
  343. }
  344. options.data = formData;
  345. }
  346. // Blob reference is not needed anymore, free memory:
  347. options.blob = null;
  348. },
  349. _initIframeSettings: function (options) {
  350. // Setting the dataType to iframe enables the iframe transport:
  351. options.dataType = 'iframe ' + (options.dataType || '');
  352. // The iframe transport accepts a serialized array as form data:
  353. options.formData = this._getFormData(options);
  354. // Add redirect url to form data on cross-domain uploads:
  355. if (options.redirect && $('<a></a>').prop('href', options.url)
  356. .prop('host') !== location.host) {
  357. options.formData.push({
  358. name: options.redirectParamName || 'redirect',
  359. value: options.redirect
  360. });
  361. }
  362. },
  363. _initDataSettings: function (options) {
  364. if (this._isXHRUpload(options)) {
  365. if (!this._chunkedUpload(options, true)) {
  366. if (!options.data) {
  367. this._initXHRData(options);
  368. }
  369. this._initProgressListener(options);
  370. }
  371. if (options.postMessage) {
  372. // Setting the dataType to postmessage enables the
  373. // postMessage transport:
  374. options.dataType = 'postmessage ' + (options.dataType || '');
  375. }
  376. } else {
  377. this._initIframeSettings(options, 'iframe');
  378. }
  379. },
  380. _getParamName: function (options) {
  381. var fileInput = $(options.fileInput),
  382. paramName = options.paramName;
  383. if (!paramName) {
  384. paramName = [];
  385. fileInput.each(function () {
  386. var input = $(this),
  387. name = input.prop('name') || 'files[]',
  388. i = (input.prop('files') || [1]).length;
  389. while (i) {
  390. paramName.push(name);
  391. i -= 1;
  392. }
  393. });
  394. if (!paramName.length) {
  395. paramName = [fileInput.prop('name') || 'files[]'];
  396. }
  397. } else if (!$.isArray(paramName)) {
  398. paramName = [paramName];
  399. }
  400. return paramName;
  401. },
  402. _initFormSettings: function (options) {
  403. // Retrieve missing options from the input field and the
  404. // associated form, if available:
  405. if (!options.form || !options.form.length) {
  406. options.form = $(options.fileInput.prop('form'));
  407. // If the given file input doesn't have an associated form,
  408. // use the default widget file input's form:
  409. if (!options.form.length) {
  410. options.form = $(this.options.fileInput.prop('form'));
  411. }
  412. }
  413. options.paramName = this._getParamName(options);
  414. if (!options.url) {
  415. options.url = options.form.prop('action') || location.href;
  416. }
  417. // The HTTP request method must be "POST" or "PUT":
  418. options.type = (options.type || options.form.prop('method') || '')
  419. .toUpperCase();
  420. if (options.type !== 'POST' && options.type !== 'PUT') {
  421. options.type = 'POST';
  422. }
  423. if (!options.formAcceptCharset) {
  424. options.formAcceptCharset = options.form.attr('accept-charset');
  425. }
  426. },
  427. _getAJAXSettings: function (data) {
  428. var options = $.extend({}, this.options, data);
  429. this._initFormSettings(options);
  430. this._initDataSettings(options);
  431. return options;
  432. },
  433. // Maps jqXHR callbacks to the equivalent
  434. // methods of the given Promise object:
  435. _enhancePromise: function (promise) {
  436. promise.success = promise.done;
  437. promise.error = promise.fail;
  438. promise.complete = promise.always;
  439. return promise;
  440. },
  441. // Creates and returns a Promise object enhanced with
  442. // the jqXHR methods abort, success, error and complete:
  443. _getXHRPromise: function (resolveOrReject, context, args) {
  444. var dfd = $.Deferred(),
  445. promise = dfd.promise();
  446. context = context || this.options.context || promise;
  447. if (resolveOrReject === true) {
  448. dfd.resolveWith(context, args);
  449. } else if (resolveOrReject === false) {
  450. dfd.rejectWith(context, args);
  451. }
  452. promise.abort = dfd.promise;
  453. return this._enhancePromise(promise);
  454. },
  455. // Parses the Range header from the server response
  456. // and returns the uploaded bytes:
  457. _getUploadedBytes: function (jqXHR) {
  458. var range = jqXHR.getResponseHeader('Range'),
  459. parts = range && range.split('-'),
  460. upperBytesPos = parts && parts.length > 1 &&
  461. parseInt(parts[1], 10);
  462. return upperBytesPos && upperBytesPos + 1;
  463. },
  464. // Uploads a file in multiple, sequential requests
  465. // by splitting the file up in multiple blob chunks.
  466. // If the second parameter is true, only tests if the file
  467. // should be uploaded in chunks, but does not invoke any
  468. // upload requests:
  469. _chunkedUpload: function (options, testOnly) {
  470. var that = this,
  471. file = options.files[0],
  472. fs = file.size,
  473. ub = options.uploadedBytes = options.uploadedBytes || 0,
  474. mcs = options.maxChunkSize || fs,
  475. slice = file.slice || file.webkitSlice || file.mozSlice,
  476. dfd = $.Deferred(),
  477. promise = dfd.promise(),
  478. jqXHR,
  479. upload;
  480. if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
  481. options.data) {
  482. return false;
  483. }
  484. if (testOnly) {
  485. return true;
  486. }
  487. if (ub >= fs) {
  488. file.error = 'Uploaded bytes exceed file size';
  489. return this._getXHRPromise(
  490. false,
  491. options.context,
  492. [null, 'error', file.error]
  493. );
  494. }
  495. // The chunk upload method:
  496. upload = function (i) {
  497. // Clone the options object for each chunk upload:
  498. var o = $.extend({}, options);
  499. o.blob = slice.call(
  500. file,
  501. ub,
  502. ub + mcs
  503. );
  504. // Store the current chunk size, as the blob itself
  505. // will be dereferenced after data processing:
  506. o.chunkSize = o.blob.size;
  507. // Expose the chunk bytes position range:
  508. o.contentRange = 'bytes ' + ub + '-' +
  509. (ub + o.chunkSize - 1) + '/' + fs;
  510. // Process the upload data (the blob and potential form data):
  511. that._initXHRData(o);
  512. // Add progress listeners for this chunk upload:
  513. that._initProgressListener(o);
  514. jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
  515. .done(function (result, textStatus, jqXHR) {
  516. ub = that._getUploadedBytes(jqXHR) ||
  517. (ub + o.chunkSize);
  518. // Create a progress event if upload is done and
  519. // no progress event has been invoked for this chunk:
  520. if (!o.loaded) {
  521. that._onProgress($.Event('progress', {
  522. lengthComputable: true,
  523. loaded: ub - o.uploadedBytes,
  524. total: ub - o.uploadedBytes
  525. }), o);
  526. }
  527. options.uploadedBytes = o.uploadedBytes = ub;
  528. if (ub < fs) {
  529. // File upload not yet complete,
  530. // continue with the next chunk:
  531. upload();
  532. } else {
  533. dfd.resolveWith(
  534. o.context,
  535. [result, textStatus, jqXHR]
  536. );
  537. }
  538. })
  539. .fail(function (jqXHR, textStatus, errorThrown) {
  540. dfd.rejectWith(
  541. o.context,
  542. [jqXHR, textStatus, errorThrown]
  543. );
  544. });
  545. };
  546. this._enhancePromise(promise);
  547. promise.abort = function () {
  548. return jqXHR.abort();
  549. };
  550. upload();
  551. return promise;
  552. },
  553. _beforeSend: function (e, data) {
  554. if (this._active === 0) {
  555. // the start callback is triggered when an upload starts
  556. // and no other uploads are currently running,
  557. // equivalent to the global ajaxStart event:
  558. this._trigger('start');
  559. // Set timer for global bitrate progress calculation:
  560. this._bitrateTimer = new this._BitrateTimer();
  561. }
  562. this._active += 1;
  563. // Initialize the global progress values:
  564. this._loaded += data.uploadedBytes || 0;
  565. this._total += this._getTotal(data.files);
  566. },
  567. _onDone: function (result, textStatus, jqXHR, options) {
  568. if (!this._isXHRUpload(options)) {
  569. // Create a progress event for each iframe load:
  570. this._onProgress($.Event('progress', {
  571. lengthComputable: true,
  572. loaded: 1,
  573. total: 1
  574. }), options);
  575. }
  576. options.result = result;
  577. options.textStatus = textStatus;
  578. options.jqXHR = jqXHR;
  579. this._trigger('done', null, options);
  580. },
  581. _onFail: function (jqXHR, textStatus, errorThrown, options) {
  582. options.jqXHR = jqXHR;
  583. options.textStatus = textStatus;
  584. options.errorThrown = errorThrown;
  585. this._trigger('fail', null, options);
  586. if (options.recalculateProgress) {
  587. // Remove the failed (error or abort) file upload from
  588. // the global progress calculation:
  589. this._loaded -= options.loaded || options.uploadedBytes || 0;
  590. this._total -= options.total || this._getTotal(options.files);
  591. }
  592. },
  593. _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
  594. this._active -= 1;
  595. options.textStatus = textStatus;
  596. if (jqXHRorError && jqXHRorError.always) {
  597. options.jqXHR = jqXHRorError;
  598. options.result = jqXHRorResult;
  599. } else {
  600. options.jqXHR = jqXHRorResult;
  601. options.errorThrown = jqXHRorError;
  602. }
  603. this._trigger('always', null, options);
  604. if (this._active === 0) {
  605. // The stop callback is triggered when all uploads have
  606. // been completed, equivalent to the global ajaxStop event:
  607. this._trigger('stop');
  608. // Reset the global progress values:
  609. this._loaded = this._total = 0;
  610. this._bitrateTimer = null;
  611. }
  612. },
  613. _onSend: function (e, data) {
  614. var that = this,
  615. jqXHR,
  616. slot,
  617. pipe,
  618. options = that._getAJAXSettings(data),
  619. send = function (resolve, args) {
  620. that._sending += 1;
  621. // Set timer for bitrate progress calculation:
  622. options._bitrateTimer = new that._BitrateTimer();
  623. jqXHR = jqXHR || (
  624. (resolve !== false &&
  625. that._trigger('send', e, options) !== false &&
  626. (that._chunkedUpload(options) || $.ajax(options))) ||
  627. that._getXHRPromise(false, options.context, args)
  628. ).done(function (result, textStatus, jqXHR) {
  629. that._onDone(result, textStatus, jqXHR, options);
  630. }).fail(function (jqXHR, textStatus, errorThrown) {
  631. that._onFail(jqXHR, textStatus, errorThrown, options);
  632. }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
  633. that._sending -= 1;
  634. that._onAlways(
  635. jqXHRorResult,
  636. textStatus,
  637. jqXHRorError,
  638. options
  639. );
  640. if (options.limitConcurrentUploads &&
  641. options.limitConcurrentUploads > that._sending) {
  642. // Start the next queued upload,
  643. // that has not been aborted:
  644. var nextSlot = that._slots.shift(),
  645. isPending;
  646. while (nextSlot) {
  647. // jQuery 1.6 doesn't provide .state(),
  648. // while jQuery 1.8+ removed .isRejected():
  649. isPending = nextSlot.state ?
  650. nextSlot.state() === 'pending' :
  651. !nextSlot.isRejected();
  652. if (isPending) {
  653. nextSlot.resolve();
  654. break;
  655. }
  656. nextSlot = that._slots.shift();
  657. }
  658. }
  659. });
  660. return jqXHR;
  661. };
  662. this._beforeSend(e, options);
  663. if (this.options.sequentialUploads ||
  664. (this.options.limitConcurrentUploads &&
  665. this.options.limitConcurrentUploads <= this._sending)) {
  666. if (this.options.limitConcurrentUploads > 1) {
  667. slot = $.Deferred();
  668. this._slots.push(slot);
  669. pipe = slot.pipe(send);
  670. } else {
  671. pipe = (this._sequence = this._sequence.pipe(send, send));
  672. }
  673. // Return the piped Promise object, enhanced with an abort method,
  674. // which is delegated to the jqXHR object of the current upload,
  675. // and jqXHR callbacks mapped to the equivalent Promise methods:
  676. pipe.abort = function () {
  677. var args = [undefined, 'abort', 'abort'];
  678. if (!jqXHR) {
  679. if (slot) {
  680. slot.rejectWith(pipe, args);
  681. }
  682. return send(false, args);
  683. }
  684. return jqXHR.abort();
  685. };
  686. return this._enhancePromise(pipe);
  687. }
  688. return send();
  689. },
  690. _onAdd: function (e, data) {
  691. var that = this,
  692. result = true,
  693. options = $.extend({}, this.options, data),
  694. limit = options.limitMultiFileUploads,
  695. paramName = this._getParamName(options),
  696. paramNameSet,
  697. paramNameSlice,
  698. fileSet,
  699. i;
  700. if (!(options.singleFileUploads || limit) ||
  701. !this._isXHRUpload(options)) {
  702. fileSet = [data.files];
  703. paramNameSet = [paramName];
  704. } else if (!options.singleFileUploads && limit) {
  705. fileSet = [];
  706. paramNameSet = [];
  707. for (i = 0; i < data.files.length; i += limit) {
  708. fileSet.push(data.files.slice(i, i + limit));
  709. paramNameSlice = paramName.slice(i, i + limit);
  710. if (!paramNameSlice.length) {
  711. paramNameSlice = paramName;
  712. }
  713. paramNameSet.push(paramNameSlice);
  714. }
  715. } else {
  716. paramNameSet = paramName;
  717. }
  718. data.originalFiles = data.files;
  719. $.each(fileSet || data.files, function (index, element) {
  720. var newData = $.extend({}, data);
  721. newData.files = fileSet ? element : [element];
  722. newData.paramName = paramNameSet[index];
  723. newData.submit = function () {
  724. newData.jqXHR = this.jqXHR =
  725. (that._trigger('submit', e, this) !== false) &&
  726. that._onSend(e, this);
  727. return this.jqXHR;
  728. };
  729. return (result = that._trigger('add', e, newData));
  730. });
  731. return result;
  732. },
  733. _replaceFileInput: function (input) {
  734. var inputClone = input.clone(true);
  735. $('<form></form>').append(inputClone)[0].reset();
  736. // Detaching allows to insert the fileInput on another form
  737. // without loosing the file input value:
  738. input.after(inputClone).detach();
  739. // Avoid memory leaks with the detached file input:
  740. $.cleanData(input.unbind('remove'));
  741. // Replace the original file input element in the fileInput
  742. // elements set with the clone, which has been copied including
  743. // event handlers:
  744. this.options.fileInput = this.options.fileInput.map(function (i, el) {
  745. if (el === input[0]) {
  746. return inputClone[0];
  747. }
  748. return el;
  749. });
  750. // If the widget has been initialized on the file input itself,
  751. // override this.element with the file input clone:
  752. if (input[0] === this.element[0]) {
  753. this.element = inputClone;
  754. }
  755. },
  756. _handleFileTreeEntry: function (entry, path) {
  757. var that = this,
  758. dfd = $.Deferred(),
  759. errorHandler = function (e) {
  760. if (e && !e.entry) {
  761. e.entry = entry;
  762. }
  763. // Since $.when returns immediately if one
  764. // Deferred is rejected, we use resolve instead.
  765. // This allows valid files and invalid items
  766. // to be returned together in one set:
  767. dfd.resolve([e]);
  768. },
  769. dirReader;
  770. path = path || '';
  771. if (entry.isFile) {
  772. if (entry._file) {
  773. // Workaround for Chrome bug #149735
  774. entry._file.relativePath = path;
  775. dfd.resolve(entry._file);
  776. } else {
  777. entry.file(function (file) {
  778. file.relativePath = path;
  779. dfd.resolve(file);
  780. }, errorHandler);
  781. }
  782. } else if (entry.isDirectory) {
  783. dirReader = entry.createReader();
  784. dirReader.readEntries(function (entries) {
  785. that._handleFileTreeEntries(
  786. entries,
  787. path + entry.name + '/'
  788. ).done(function (files) {
  789. dfd.resolve(files);
  790. }).fail(errorHandler);
  791. }, errorHandler);
  792. } else {
  793. // Return an empy list for file system items
  794. // other than files or directories:
  795. dfd.resolve([]);
  796. }
  797. return dfd.promise();
  798. },
  799. _handleFileTreeEntries: function (entries, path) {
  800. var that = this;
  801. return $.when.apply(
  802. $,
  803. $.map(entries, function (entry) {
  804. return that._handleFileTreeEntry(entry, path);
  805. })
  806. ).pipe(function () {
  807. return Array.prototype.concat.apply(
  808. [],
  809. arguments
  810. );
  811. });
  812. },
  813. _getDroppedFiles: function (dataTransfer) {
  814. dataTransfer = dataTransfer || {};
  815. var items = dataTransfer.items;
  816. if (items && items.length && (items[0].webkitGetAsEntry ||
  817. items[0].getAsEntry)) {
  818. return this._handleFileTreeEntries(
  819. $.map(items, function (item) {
  820. var entry;
  821. if (item.webkitGetAsEntry) {
  822. entry = item.webkitGetAsEntry();
  823. if (entry) {
  824. // Workaround for Chrome bug #149735:
  825. entry._file = item.getAsFile();
  826. }
  827. return entry;
  828. }
  829. return item.getAsEntry();
  830. })
  831. );
  832. }
  833. return $.Deferred().resolve(
  834. $.makeArray(dataTransfer.files)
  835. ).promise();
  836. },
  837. _getSingleFileInputFiles: function (fileInput) {
  838. fileInput = $(fileInput);
  839. var entries = fileInput.prop('webkitEntries') ||
  840. fileInput.prop('entries'),
  841. files,
  842. value;
  843. if (entries && entries.length) {
  844. return this._handleFileTreeEntries(entries);
  845. }
  846. files = $.makeArray(fileInput.prop('files'));
  847. if (!files.length) {
  848. value = fileInput.prop('value');
  849. if (!value) {
  850. return $.Deferred().resolve([]).promise();
  851. }
  852. // If the files property is not available, the browser does not
  853. // support the File API and we add a pseudo File object with
  854. // the input value as name with path information removed:
  855. files = [{name: value.replace(/^.*\\/, '')}];
  856. } else if (files[0].name === undefined && files[0].fileName) {
  857. // File normalization for Safari 4 and Firefox 3:
  858. $.each(files, function (index, file) {
  859. file.name = file.fileName;
  860. file.size = file.fileSize;
  861. });
  862. }
  863. return $.Deferred().resolve(files).promise();
  864. },
  865. _getFileInputFiles: function (fileInput) {
  866. if (!(fileInput instanceof $) || fileInput.length === 1) {
  867. return this._getSingleFileInputFiles(fileInput);
  868. }
  869. return $.when.apply(
  870. $,
  871. $.map(fileInput, this._getSingleFileInputFiles)
  872. ).pipe(function () {
  873. return Array.prototype.concat.apply(
  874. [],
  875. arguments
  876. );
  877. });
  878. },
  879. _onChange: function (e) {
  880. var that = this,
  881. data = {
  882. fileInput: $(e.target),
  883. form: $(e.target.form)
  884. };
  885. this._getFileInputFiles(data.fileInput).always(function (files) {
  886. data.files = files;
  887. if (that.options.replaceFileInput) {
  888. that._replaceFileInput(data.fileInput);
  889. }
  890. if (that._trigger('change', e, data) !== false) {
  891. that._onAdd(e, data);
  892. }
  893. });
  894. },
  895. _onPaste: function (e) {
  896. var cbd = e.originalEvent.clipboardData,
  897. items = (cbd && cbd.items) || [],
  898. data = {files: []};
  899. $.each(items, function (index, item) {
  900. var file = item.getAsFile && item.getAsFile();
  901. if (file) {
  902. data.files.push(file);
  903. }
  904. });
  905. if (this._trigger('paste', e, data) === false ||
  906. this._onAdd(e, data) === false) {
  907. return false;
  908. }
  909. },
  910. _onDrop: function (e) {
  911. e.preventDefault();
  912. var that = this,
  913. dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
  914. data = {};
  915. this._getDroppedFiles(dataTransfer).always(function (files) {
  916. data.files = files;
  917. if (that._trigger('drop', e, data) !== false) {
  918. that._onAdd(e, data);
  919. }
  920. });
  921. },
  922. _onDragOver: function (e) {
  923. var dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
  924. if (this._trigger('dragover', e) === false) {
  925. return false;
  926. }
  927. if (dataTransfer) {
  928. dataTransfer.dropEffect = 'copy';
  929. }
  930. e.preventDefault();
  931. },
  932. _initEventHandlers: function () {
  933. if (this._isXHRUpload(this.options)) {
  934. this._on(this.options.dropZone, {
  935. dragover: this._onDragOver,
  936. drop: this._onDrop
  937. });
  938. this._on(this.options.pasteZone, {
  939. paste: this._onPaste
  940. });
  941. }
  942. this._on(this.options.fileInput, {
  943. change: this._onChange
  944. });
  945. },
  946. _destroyEventHandlers: function () {
  947. this._off(this.options.dropZone, 'dragover drop');
  948. this._off(this.options.pasteZone, 'paste');
  949. this._off(this.options.fileInput, 'change');
  950. },
  951. _setOption: function (key, value) {
  952. var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
  953. if (refresh) {
  954. this._destroyEventHandlers();
  955. }
  956. this._super(key, value);
  957. if (refresh) {
  958. this._initSpecialOptions();
  959. this._initEventHandlers();
  960. }
  961. },
  962. _initSpecialOptions: function () {
  963. var options = this.options;
  964. if (options.fileInput === undefined) {
  965. options.fileInput = this.element.is('input[type="file"]') ?
  966. this.element : this.element.find('input[type="file"]');
  967. } else if (!(options.fileInput instanceof $)) {
  968. options.fileInput = $(options.fileInput);
  969. }
  970. if (!(options.dropZone instanceof $)) {
  971. options.dropZone = $(options.dropZone);
  972. }
  973. if (!(options.pasteZone instanceof $)) {
  974. options.pasteZone = $(options.pasteZone);
  975. }
  976. },
  977. _create: function () {
  978. var options = this.options;
  979. // Initialize options set via HTML5 data-attributes:
  980. $.extend(options, $(this.element[0].cloneNode(false)).data());
  981. this._initSpecialOptions();
  982. this._slots = [];
  983. this._sequence = this._getXHRPromise(true);
  984. this._sending = this._active = this._loaded = this._total = 0;
  985. this._initEventHandlers();
  986. },
  987. _destroy: function () {
  988. this._destroyEventHandlers();
  989. },
  990. // This method is exposed to the widget API and allows adding files
  991. // using the fileupload API. The data parameter accepts an object which
  992. // must have a files property and can contain additional options:
  993. // .fileupload('add', {files: filesList});
  994. add: function (data) {
  995. var that = this;
  996. if (!data || this.options.disabled) {
  997. return;
  998. }
  999. if (data.fileInput && !data.files) {
  1000. this._getFileInputFiles(data.fileInput).always(function (files) {
  1001. data.files = files;
  1002. that._onAdd(null, data);
  1003. });
  1004. } else {
  1005. data.files = $.makeArray(data.files);
  1006. this._onAdd(null, data);
  1007. }
  1008. },
  1009. // This method is exposed to the widget API and allows sending files
  1010. // using the fileupload API. The data parameter accepts an object which
  1011. // must have a files or fileInput property and can contain additional options:
  1012. // .fileupload('send', {files: filesList});
  1013. // The method returns a Promise object for the file upload call.
  1014. send: function (data) {
  1015. if (data && !this.options.disabled) {
  1016. if (data.fileInput && !data.files) {
  1017. var that = this,
  1018. dfd = $.Deferred(),
  1019. promise = dfd.promise(),
  1020. jqXHR,
  1021. aborted;
  1022. promise.abort = function () {
  1023. aborted = true;
  1024. if (jqXHR) {
  1025. return jqXHR.abort();
  1026. }
  1027. dfd.reject(null, 'abort', 'abort');
  1028. return promise;
  1029. };
  1030. this._getFileInputFiles(data.fileInput).always(
  1031. function (files) {
  1032. if (aborted) {
  1033. return;
  1034. }
  1035. data.files = files;
  1036. jqXHR = that._onSend(null, data).then(
  1037. function (result, textStatus, jqXHR) {
  1038. dfd.resolve(result, textStatus, jqXHR);
  1039. },
  1040. function (jqXHR, textStatus, errorThrown) {
  1041. dfd.reject(jqXHR, textStatus, errorThrown);
  1042. }
  1043. );
  1044. }
  1045. );
  1046. return this._enhancePromise(promise);
  1047. }
  1048. data.files = $.makeArray(data.files);
  1049. if (data.files.length) {
  1050. return this._onSend(null, data);
  1051. }
  1052. }
  1053. return this._getXHRPromise(false, data && data.context);
  1054. }
  1055. });
  1056. }));