jquery.fileupload.js 46 KB

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