jquery.fileupload.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. /*
  2. * jQuery File Upload Plugin 5.19.7
  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. // 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. formData.append(paramName, options.blob, file.name);
  328. } else {
  329. $.each(options.files, function (index, file) {
  330. // Files are also Blob instances, but some browsers
  331. // (Firefox 3.6) support the File API but not Blobs.
  332. // This check allows the tests to run with
  333. // dummy objects:
  334. if ((window.Blob && file instanceof Blob) ||
  335. (window.File && file instanceof File)) {
  336. formData.append(
  337. options.paramName[index] || paramName,
  338. file,
  339. file.name
  340. );
  341. }
  342. });
  343. }
  344. }
  345. options.data = formData;
  346. }
  347. // Blob reference is not needed anymore, free memory:
  348. options.blob = null;
  349. },
  350. _initIframeSettings: function (options) {
  351. // Setting the dataType to iframe enables the iframe transport:
  352. options.dataType = 'iframe ' + (options.dataType || '');
  353. // The iframe transport accepts a serialized array as form data:
  354. options.formData = this._getFormData(options);
  355. // Add redirect url to form data on cross-domain uploads:
  356. if (options.redirect && $('<a></a>').prop('href', options.url)
  357. .prop('host') !== location.host) {
  358. options.formData.push({
  359. name: options.redirectParamName || 'redirect',
  360. value: options.redirect
  361. });
  362. }
  363. },
  364. _initDataSettings: function (options) {
  365. if (this._isXHRUpload(options)) {
  366. if (!this._chunkedUpload(options, true)) {
  367. if (!options.data) {
  368. this._initXHRData(options);
  369. }
  370. this._initProgressListener(options);
  371. }
  372. if (options.postMessage) {
  373. // Setting the dataType to postmessage enables the
  374. // postMessage transport:
  375. options.dataType = 'postmessage ' + (options.dataType || '');
  376. }
  377. } else {
  378. this._initIframeSettings(options, 'iframe');
  379. }
  380. },
  381. _getParamName: function (options) {
  382. var fileInput = $(options.fileInput),
  383. paramName = options.paramName;
  384. if (!paramName) {
  385. paramName = [];
  386. fileInput.each(function () {
  387. var input = $(this),
  388. name = input.prop('name') || 'files[]',
  389. i = (input.prop('files') || [1]).length;
  390. while (i) {
  391. paramName.push(name);
  392. i -= 1;
  393. }
  394. });
  395. if (!paramName.length) {
  396. paramName = [fileInput.prop('name') || 'files[]'];
  397. }
  398. } else if (!$.isArray(paramName)) {
  399. paramName = [paramName];
  400. }
  401. return paramName;
  402. },
  403. _initFormSettings: function (options) {
  404. // Retrieve missing options from the input field and the
  405. // associated form, if available:
  406. if (!options.form || !options.form.length) {
  407. options.form = $(options.fileInput.prop('form'));
  408. // If the given file input doesn't have an associated form,
  409. // use the default widget file input's form:
  410. if (!options.form.length) {
  411. options.form = $(this.options.fileInput.prop('form'));
  412. }
  413. }
  414. options.paramName = this._getParamName(options);
  415. if (!options.url) {
  416. options.url = options.form.prop('action') || location.href;
  417. }
  418. // The HTTP request method must be "POST" or "PUT":
  419. options.type = (options.type || options.form.prop('method') || '')
  420. .toUpperCase();
  421. if (options.type !== 'POST' && options.type !== 'PUT') {
  422. options.type = 'POST';
  423. }
  424. if (!options.formAcceptCharset) {
  425. options.formAcceptCharset = options.form.attr('accept-charset');
  426. }
  427. },
  428. _getAJAXSettings: function (data) {
  429. var options = $.extend({}, this.options, data);
  430. this._initFormSettings(options);
  431. this._initDataSettings(options);
  432. return options;
  433. },
  434. // Maps jqXHR callbacks to the equivalent
  435. // methods of the given Promise object:
  436. _enhancePromise: function (promise) {
  437. promise.success = promise.done;
  438. promise.error = promise.fail;
  439. promise.complete = promise.always;
  440. return promise;
  441. },
  442. // Creates and returns a Promise object enhanced with
  443. // the jqXHR methods abort, success, error and complete:
  444. _getXHRPromise: function (resolveOrReject, context, args) {
  445. var dfd = $.Deferred(),
  446. promise = dfd.promise();
  447. context = context || this.options.context || promise;
  448. if (resolveOrReject === true) {
  449. dfd.resolveWith(context, args);
  450. } else if (resolveOrReject === false) {
  451. dfd.rejectWith(context, args);
  452. }
  453. promise.abort = dfd.promise;
  454. return this._enhancePromise(promise);
  455. },
  456. // Parses the Range header from the server response
  457. // and returns the uploaded bytes:
  458. _getUploadedBytes: function (jqXHR) {
  459. var range = jqXHR.getResponseHeader('Range'),
  460. parts = range && range.split('-'),
  461. upperBytesPos = parts && parts.length > 1 &&
  462. parseInt(parts[1], 10);
  463. return upperBytesPos && upperBytesPos + 1;
  464. },
  465. // Uploads a file in multiple, sequential requests
  466. // by splitting the file up in multiple blob chunks.
  467. // If the second parameter is true, only tests if the file
  468. // should be uploaded in chunks, but does not invoke any
  469. // upload requests:
  470. _chunkedUpload: function (options, testOnly) {
  471. var that = this,
  472. file = options.files[0],
  473. fs = file.size,
  474. ub = options.uploadedBytes = options.uploadedBytes || 0,
  475. mcs = options.maxChunkSize || fs,
  476. slice = file.slice || file.webkitSlice || file.mozSlice,
  477. dfd = $.Deferred(),
  478. promise = dfd.promise(),
  479. jqXHR,
  480. upload;
  481. if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
  482. options.data) {
  483. return false;
  484. }
  485. if (testOnly) {
  486. return true;
  487. }
  488. if (ub >= fs) {
  489. file.error = 'Uploaded bytes exceed file size';
  490. return this._getXHRPromise(
  491. false,
  492. options.context,
  493. [null, 'error', file.error]
  494. );
  495. }
  496. // The chunk upload method:
  497. upload = function (i) {
  498. // Clone the options object for each chunk upload:
  499. var o = $.extend({}, options);
  500. o.blob = slice.call(
  501. file,
  502. ub,
  503. ub + mcs,
  504. file.type
  505. );
  506. // Store the current chunk size, as the blob itself
  507. // will be dereferenced after data processing:
  508. o.chunkSize = o.blob.size;
  509. // Expose the chunk bytes position range:
  510. o.contentRange = 'bytes ' + ub + '-' +
  511. (ub + o.chunkSize - 1) + '/' + fs;
  512. // Process the upload data (the blob and potential form data):
  513. that._initXHRData(o);
  514. // Add progress listeners for this chunk upload:
  515. that._initProgressListener(o);
  516. jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
  517. .done(function (result, textStatus, jqXHR) {
  518. ub = that._getUploadedBytes(jqXHR) ||
  519. (ub + o.chunkSize);
  520. // Create a progress event if upload is done and
  521. // no progress event has been invoked for this chunk:
  522. if (!o.loaded) {
  523. that._onProgress($.Event('progress', {
  524. lengthComputable: true,
  525. loaded: ub - o.uploadedBytes,
  526. total: ub - o.uploadedBytes
  527. }), o);
  528. }
  529. options.uploadedBytes = o.uploadedBytes = ub;
  530. if (ub < fs) {
  531. // File upload not yet complete,
  532. // continue with the next chunk:
  533. upload();
  534. } else {
  535. dfd.resolveWith(
  536. o.context,
  537. [result, textStatus, jqXHR]
  538. );
  539. }
  540. })
  541. .fail(function (jqXHR, textStatus, errorThrown) {
  542. dfd.rejectWith(
  543. o.context,
  544. [jqXHR, textStatus, errorThrown]
  545. );
  546. });
  547. };
  548. this._enhancePromise(promise);
  549. promise.abort = function () {
  550. return jqXHR.abort();
  551. };
  552. upload();
  553. return promise;
  554. },
  555. _beforeSend: function (e, data) {
  556. if (this._active === 0) {
  557. // the start callback is triggered when an upload starts
  558. // and no other uploads are currently running,
  559. // equivalent to the global ajaxStart event:
  560. this._trigger('start');
  561. // Set timer for global bitrate progress calculation:
  562. this._bitrateTimer = new this._BitrateTimer();
  563. }
  564. this._active += 1;
  565. // Initialize the global progress values:
  566. this._loaded += data.uploadedBytes || 0;
  567. this._total += this._getTotal(data.files);
  568. },
  569. _onDone: function (result, textStatus, jqXHR, options) {
  570. if (!this._isXHRUpload(options)) {
  571. // Create a progress event for each iframe load:
  572. this._onProgress($.Event('progress', {
  573. lengthComputable: true,
  574. loaded: 1,
  575. total: 1
  576. }), options);
  577. }
  578. options.result = result;
  579. options.textStatus = textStatus;
  580. options.jqXHR = jqXHR;
  581. this._trigger('done', null, options);
  582. },
  583. _onFail: function (jqXHR, textStatus, errorThrown, options) {
  584. options.jqXHR = jqXHR;
  585. options.textStatus = textStatus;
  586. options.errorThrown = errorThrown;
  587. this._trigger('fail', null, options);
  588. if (options.recalculateProgress) {
  589. // Remove the failed (error or abort) file upload from
  590. // the global progress calculation:
  591. this._loaded -= options.loaded || options.uploadedBytes || 0;
  592. this._total -= options.total || this._getTotal(options.files);
  593. }
  594. },
  595. _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
  596. this._active -= 1;
  597. options.textStatus = textStatus;
  598. if (jqXHRorError && jqXHRorError.always) {
  599. options.jqXHR = jqXHRorError;
  600. options.result = jqXHRorResult;
  601. } else {
  602. options.jqXHR = jqXHRorResult;
  603. options.errorThrown = jqXHRorError;
  604. }
  605. this._trigger('always', null, options);
  606. if (this._active === 0) {
  607. // The stop callback is triggered when all uploads have
  608. // been completed, equivalent to the global ajaxStop event:
  609. this._trigger('stop');
  610. // Reset the global progress values:
  611. this._loaded = this._total = 0;
  612. this._bitrateTimer = null;
  613. }
  614. },
  615. _onSend: function (e, data) {
  616. var that = this,
  617. jqXHR,
  618. aborted,
  619. slot,
  620. pipe,
  621. options = that._getAJAXSettings(data),
  622. send = function () {
  623. that._sending += 1;
  624. // Set timer for bitrate progress calculation:
  625. options._bitrateTimer = new that._BitrateTimer();
  626. jqXHR = jqXHR || (
  627. ((aborted || that._trigger('send', e, options) === false) &&
  628. that._getXHRPromise(false, options.context, aborted)) ||
  629. that._chunkedUpload(options) || $.ajax(options)
  630. ).done(function (result, textStatus, jqXHR) {
  631. that._onDone(result, textStatus, jqXHR, options);
  632. }).fail(function (jqXHR, textStatus, errorThrown) {
  633. that._onFail(jqXHR, textStatus, errorThrown, options);
  634. }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
  635. that._sending -= 1;
  636. that._onAlways(
  637. jqXHRorResult,
  638. textStatus,
  639. jqXHRorError,
  640. options
  641. );
  642. if (options.limitConcurrentUploads &&
  643. options.limitConcurrentUploads > that._sending) {
  644. // Start the next queued upload,
  645. // that has not been aborted:
  646. var nextSlot = that._slots.shift(),
  647. isPending;
  648. while (nextSlot) {
  649. // jQuery 1.6 doesn't provide .state(),
  650. // while jQuery 1.8+ removed .isRejected():
  651. isPending = nextSlot.state ?
  652. nextSlot.state() === 'pending' :
  653. !nextSlot.isRejected();
  654. if (isPending) {
  655. nextSlot.resolve();
  656. break;
  657. }
  658. nextSlot = that._slots.shift();
  659. }
  660. }
  661. });
  662. return jqXHR;
  663. };
  664. this._beforeSend(e, options);
  665. if (this.options.sequentialUploads ||
  666. (this.options.limitConcurrentUploads &&
  667. this.options.limitConcurrentUploads <= this._sending)) {
  668. if (this.options.limitConcurrentUploads > 1) {
  669. slot = $.Deferred();
  670. this._slots.push(slot);
  671. pipe = slot.pipe(send);
  672. } else {
  673. pipe = (this._sequence = this._sequence.pipe(send, send));
  674. }
  675. // Return the piped Promise object, enhanced with an abort method,
  676. // which is delegated to the jqXHR object of the current upload,
  677. // and jqXHR callbacks mapped to the equivalent Promise methods:
  678. pipe.abort = function () {
  679. aborted = [undefined, 'abort', 'abort'];
  680. if (!jqXHR) {
  681. if (slot) {
  682. slot.rejectWith(options.context, aborted);
  683. }
  684. return send();
  685. }
  686. return jqXHR.abort();
  687. };
  688. return this._enhancePromise(pipe);
  689. }
  690. return send();
  691. },
  692. _onAdd: function (e, data) {
  693. var that = this,
  694. result = true,
  695. options = $.extend({}, this.options, data),
  696. limit = options.limitMultiFileUploads,
  697. paramName = this._getParamName(options),
  698. paramNameSet,
  699. paramNameSlice,
  700. fileSet,
  701. i;
  702. if (!(options.singleFileUploads || limit) ||
  703. !this._isXHRUpload(options)) {
  704. fileSet = [data.files];
  705. paramNameSet = [paramName];
  706. } else if (!options.singleFileUploads && limit) {
  707. fileSet = [];
  708. paramNameSet = [];
  709. for (i = 0; i < data.files.length; i += limit) {
  710. fileSet.push(data.files.slice(i, i + limit));
  711. paramNameSlice = paramName.slice(i, i + limit);
  712. if (!paramNameSlice.length) {
  713. paramNameSlice = paramName;
  714. }
  715. paramNameSet.push(paramNameSlice);
  716. }
  717. } else {
  718. paramNameSet = paramName;
  719. }
  720. data.originalFiles = data.files;
  721. $.each(fileSet || data.files, function (index, element) {
  722. var newData = $.extend({}, data);
  723. newData.files = fileSet ? element : [element];
  724. newData.paramName = paramNameSet[index];
  725. newData.submit = function () {
  726. newData.jqXHR = this.jqXHR =
  727. (that._trigger('submit', e, this) !== false) &&
  728. that._onSend(e, this);
  729. return this.jqXHR;
  730. };
  731. result = that._trigger('add', e, newData);
  732. return result;
  733. });
  734. return result;
  735. },
  736. _replaceFileInput: function (input) {
  737. var inputClone = input.clone(true);
  738. $('<form></form>').append(inputClone)[0].reset();
  739. // Detaching allows to insert the fileInput on another form
  740. // without loosing the file input value:
  741. input.after(inputClone).detach();
  742. // Avoid memory leaks with the detached file input:
  743. $.cleanData(input.unbind('remove'));
  744. // Replace the original file input element in the fileInput
  745. // elements set with the clone, which has been copied including
  746. // event handlers:
  747. this.options.fileInput = this.options.fileInput.map(function (i, el) {
  748. if (el === input[0]) {
  749. return inputClone[0];
  750. }
  751. return el;
  752. });
  753. // If the widget has been initialized on the file input itself,
  754. // override this.element with the file input clone:
  755. if (input[0] === this.element[0]) {
  756. this.element = inputClone;
  757. }
  758. },
  759. _handleFileTreeEntry: function (entry, path) {
  760. var that = this,
  761. dfd = $.Deferred(),
  762. errorHandler = function (e) {
  763. if (e && !e.entry) {
  764. e.entry = entry;
  765. }
  766. // Since $.when returns immediately if one
  767. // Deferred is rejected, we use resolve instead.
  768. // This allows valid files and invalid items
  769. // to be returned together in one set:
  770. dfd.resolve([e]);
  771. },
  772. dirReader;
  773. path = path || '';
  774. if (entry.isFile) {
  775. if (entry._file) {
  776. // Workaround for Chrome bug #149735
  777. entry._file.relativePath = path;
  778. dfd.resolve(entry._file);
  779. } else {
  780. entry.file(function (file) {
  781. file.relativePath = path;
  782. dfd.resolve(file);
  783. }, errorHandler);
  784. }
  785. } else if (entry.isDirectory) {
  786. dirReader = entry.createReader();
  787. dirReader.readEntries(function (entries) {
  788. that._handleFileTreeEntries(
  789. entries,
  790. path + entry.name + '/'
  791. ).done(function (files) {
  792. dfd.resolve(files);
  793. }).fail(errorHandler);
  794. }, errorHandler);
  795. } else {
  796. // Return an empy list for file system items
  797. // other than files or directories:
  798. dfd.resolve([]);
  799. }
  800. return dfd.promise();
  801. },
  802. _handleFileTreeEntries: function (entries, path) {
  803. var that = this;
  804. return $.when.apply(
  805. $,
  806. $.map(entries, function (entry) {
  807. return that._handleFileTreeEntry(entry, path);
  808. })
  809. ).pipe(function () {
  810. return Array.prototype.concat.apply(
  811. [],
  812. arguments
  813. );
  814. });
  815. },
  816. _getDroppedFiles: function (dataTransfer) {
  817. dataTransfer = dataTransfer || {};
  818. var items = dataTransfer.items;
  819. if (items && items.length && (items[0].webkitGetAsEntry ||
  820. items[0].getAsEntry)) {
  821. return this._handleFileTreeEntries(
  822. $.map(items, function (item) {
  823. var entry;
  824. if (item.webkitGetAsEntry) {
  825. entry = item.webkitGetAsEntry();
  826. if (entry) {
  827. // Workaround for Chrome bug #149735:
  828. entry._file = item.getAsFile();
  829. }
  830. return entry;
  831. }
  832. return item.getAsEntry();
  833. })
  834. );
  835. }
  836. return $.Deferred().resolve(
  837. $.makeArray(dataTransfer.files)
  838. ).promise();
  839. },
  840. _getSingleFileInputFiles: function (fileInput) {
  841. fileInput = $(fileInput);
  842. var entries = fileInput.prop('webkitEntries') ||
  843. fileInput.prop('entries'),
  844. files,
  845. value;
  846. if (entries && entries.length) {
  847. return this._handleFileTreeEntries(entries);
  848. }
  849. files = $.makeArray(fileInput.prop('files'));
  850. if (!files.length) {
  851. value = fileInput.prop('value');
  852. if (!value) {
  853. return $.Deferred().resolve([]).promise();
  854. }
  855. // If the files property is not available, the browser does not
  856. // support the File API and we add a pseudo File object with
  857. // the input value as name with path information removed:
  858. files = [{name: value.replace(/^.*\\/, '')}];
  859. } else if (files[0].name === undefined && files[0].fileName) {
  860. // File normalization for Safari 4 and Firefox 3:
  861. $.each(files, function (index, file) {
  862. file.name = file.fileName;
  863. file.size = file.fileSize;
  864. });
  865. }
  866. return $.Deferred().resolve(files).promise();
  867. },
  868. _getFileInputFiles: function (fileInput) {
  869. if (!(fileInput instanceof $) || fileInput.length === 1) {
  870. return this._getSingleFileInputFiles(fileInput);
  871. }
  872. return $.when.apply(
  873. $,
  874. $.map(fileInput, this._getSingleFileInputFiles)
  875. ).pipe(function () {
  876. return Array.prototype.concat.apply(
  877. [],
  878. arguments
  879. );
  880. });
  881. },
  882. _onChange: function (e) {
  883. var that = this,
  884. data = {
  885. fileInput: $(e.target),
  886. form: $(e.target.form)
  887. };
  888. this._getFileInputFiles(data.fileInput).always(function (files) {
  889. data.files = files;
  890. if (that.options.replaceFileInput) {
  891. that._replaceFileInput(data.fileInput);
  892. }
  893. if (that._trigger('change', e, data) !== false) {
  894. that._onAdd(e, data);
  895. }
  896. });
  897. },
  898. _onPaste: function (e) {
  899. return true;
  900. var cbd = e.originalEvent.clipboardData,
  901. items = (cbd && cbd.items) || [],
  902. data = {files: []};
  903. $.each(items, function (index, item) {
  904. var file = item.getAsFile && item.getAsFile();
  905. if (file) {
  906. data.files.push(file);
  907. }
  908. });
  909. if (this._trigger('paste', e, data) === false ||
  910. this._onAdd(e, data) === false) {
  911. return false;
  912. }
  913. },
  914. _onDrop: function (e) {
  915. var that = this,
  916. dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
  917. data = {};
  918. if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
  919. e.preventDefault();
  920. }
  921. this._getDroppedFiles(dataTransfer).always(function (files) {
  922. data.files = files;
  923. if (that._trigger('drop', e, data) !== false) {
  924. that._onAdd(e, data);
  925. }
  926. });
  927. },
  928. _onDragOver: function (e) {
  929. var dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
  930. if (this._trigger('dragover', e) === false) {
  931. return false;
  932. }
  933. if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1) {
  934. dataTransfer.dropEffect = 'copy';
  935. e.preventDefault();
  936. }
  937. },
  938. _initEventHandlers: function () {
  939. if (this._isXHRUpload(this.options)) {
  940. this._on(this.options.dropZone, {
  941. dragover: this._onDragOver,
  942. drop: this._onDrop
  943. });
  944. this._on(this.options.pasteZone, {
  945. paste: this._onPaste
  946. });
  947. }
  948. this._on(this.options.fileInput, {
  949. change: this._onChange
  950. });
  951. },
  952. _destroyEventHandlers: function () {
  953. this._off(this.options.dropZone, 'dragover drop');
  954. this._off(this.options.pasteZone, 'paste');
  955. this._off(this.options.fileInput, 'change');
  956. },
  957. _setOption: function (key, value) {
  958. var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
  959. if (refresh) {
  960. this._destroyEventHandlers();
  961. }
  962. this._super(key, value);
  963. if (refresh) {
  964. this._initSpecialOptions();
  965. this._initEventHandlers();
  966. }
  967. },
  968. _initSpecialOptions: function () {
  969. var options = this.options;
  970. if (options.fileInput === undefined) {
  971. options.fileInput = this.element.is('input[type="file"]') ?
  972. this.element : this.element.find('input[type="file"]');
  973. } else if (!(options.fileInput instanceof $)) {
  974. options.fileInput = $(options.fileInput);
  975. }
  976. if (!(options.dropZone instanceof $)) {
  977. options.dropZone = $(options.dropZone);
  978. }
  979. if (!(options.pasteZone instanceof $)) {
  980. options.pasteZone = $(options.pasteZone);
  981. }
  982. },
  983. _create: function () {
  984. var options = this.options;
  985. // Initialize options set via HTML5 data-attributes:
  986. $.extend(options, $(this.element[0].cloneNode(false)).data());
  987. this._initSpecialOptions();
  988. this._slots = [];
  989. this._sequence = this._getXHRPromise(true);
  990. this._sending = this._active = this._loaded = this._total = 0;
  991. this._initEventHandlers();
  992. },
  993. _destroy: function () {
  994. this._destroyEventHandlers();
  995. },
  996. // This method is exposed to the widget API and allows adding files
  997. // using the fileupload API. The data parameter accepts an object which
  998. // must have a files property and can contain additional options:
  999. // .fileupload('add', {files: filesList});
  1000. add: function (data) {
  1001. var that = this;
  1002. if (!data || this.options.disabled) {
  1003. return;
  1004. }
  1005. if (data.fileInput && !data.files) {
  1006. this._getFileInputFiles(data.fileInput).always(function (files) {
  1007. data.files = files;
  1008. that._onAdd(null, data);
  1009. });
  1010. } else {
  1011. data.files = $.makeArray(data.files);
  1012. this._onAdd(null, data);
  1013. }
  1014. },
  1015. // This method is exposed to the widget API and allows sending files
  1016. // using the fileupload API. The data parameter accepts an object which
  1017. // must have a files or fileInput property and can contain additional options:
  1018. // .fileupload('send', {files: filesList});
  1019. // The method returns a Promise object for the file upload call.
  1020. send: function (data) {
  1021. if (data && !this.options.disabled) {
  1022. if (data.fileInput && !data.files) {
  1023. var that = this,
  1024. dfd = $.Deferred(),
  1025. promise = dfd.promise(),
  1026. jqXHR,
  1027. aborted;
  1028. promise.abort = function () {
  1029. aborted = true;
  1030. if (jqXHR) {
  1031. return jqXHR.abort();
  1032. }
  1033. dfd.reject(null, 'abort', 'abort');
  1034. return promise;
  1035. };
  1036. this._getFileInputFiles(data.fileInput).always(
  1037. function (files) {
  1038. if (aborted) {
  1039. return;
  1040. }
  1041. data.files = files;
  1042. jqXHR = that._onSend(null, data).then(
  1043. function (result, textStatus, jqXHR) {
  1044. dfd.resolve(result, textStatus, jqXHR);
  1045. },
  1046. function (jqXHR, textStatus, errorThrown) {
  1047. dfd.reject(jqXHR, textStatus, errorThrown);
  1048. }
  1049. );
  1050. }
  1051. );
  1052. return this._enhancePromise(promise);
  1053. }
  1054. data.files = $.makeArray(data.files);
  1055. if (data.files.length) {
  1056. return this._onSend(null, data);
  1057. }
  1058. }
  1059. return this._getXHRPromise(false, data && data.context);
  1060. }
  1061. });
  1062. }));