jquery.fileupload-ui.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. /*
  2. * jQuery File Upload User Interface Plugin
  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. * https://opensource.org/licenses/MIT
  10. */
  11. /* global define, require */
  12. (function(factory) {
  13. 'use strict';
  14. if (typeof define === 'function' && define.amd) {
  15. // Register as an anonymous AMD module:
  16. define([
  17. 'jquery',
  18. 'blueimp-tmpl',
  19. './jquery.fileupload-image',
  20. './jquery.fileupload-audio',
  21. './jquery.fileupload-video',
  22. './jquery.fileupload-validate'
  23. ], factory);
  24. } else if (typeof exports === 'object') {
  25. // Node/CommonJS:
  26. factory(
  27. require('jquery'),
  28. require('blueimp-tmpl'),
  29. require('./jquery.fileupload-image'),
  30. require('./jquery.fileupload-audio'),
  31. require('./jquery.fileupload-video'),
  32. require('./jquery.fileupload-validate')
  33. );
  34. } else {
  35. // Browser globals:
  36. factory(window.jQuery, window.tmpl);
  37. }
  38. })(function($, tmpl) {
  39. 'use strict';
  40. $.blueimp.fileupload.prototype._specialOptions.push(
  41. 'filesContainer',
  42. 'uploadTemplateId',
  43. 'downloadTemplateId'
  44. );
  45. // The UI version extends the file upload widget
  46. // and adds complete user interface interaction:
  47. $.widget('blueimp.fileupload', $.blueimp.fileupload, {
  48. options: {
  49. // By default, files added to the widget are uploaded as soon
  50. // as the user clicks on the start buttons. To enable automatic
  51. // uploads, set the following option to true:
  52. autoUpload: false,
  53. // The ID of the upload template:
  54. uploadTemplateId: 'template-upload',
  55. // The ID of the download template:
  56. downloadTemplateId: 'template-download',
  57. // The container for the list of files. If undefined, it is set to
  58. // an element with class "files" inside of the widget element:
  59. filesContainer: undefined,
  60. // By default, files are appended to the files container.
  61. // Set the following option to true, to prepend files instead:
  62. prependFiles: false,
  63. // The expected data type of the upload response, sets the dataType
  64. // option of the $.ajax upload requests:
  65. dataType: 'json',
  66. // Error and info messages:
  67. messages: {
  68. unknownError: 'Unknown error'
  69. },
  70. // Function returning the current number of files,
  71. // used by the maxNumberOfFiles validation:
  72. getNumberOfFiles: function() {
  73. return this.filesContainer.children().not('.processing').length;
  74. },
  75. // Callback to retrieve the list of files from the server response:
  76. getFilesFromResponse: function(data) {
  77. if (data.result && $.isArray(data.result.files)) {
  78. return data.result.files;
  79. }
  80. return [];
  81. },
  82. // The add callback is invoked as soon as files are added to the fileupload
  83. // widget (via file input selection, drag & drop or add API call).
  84. // See the basic file upload widget for more information:
  85. add: function(e, data) {
  86. if (e.isDefaultPrevented()) {
  87. return false;
  88. }
  89. var $this = $(this),
  90. that = $this.data('blueimp-fileupload') || $this.data('fileupload'),
  91. options = that.options;
  92. data.context = that
  93. ._renderUpload(data.files)
  94. .data('data', data)
  95. .addClass('processing');
  96. options.filesContainer[options.prependFiles ? 'prepend' : 'append'](
  97. data.context
  98. );
  99. that._forceReflow(data.context);
  100. that._transition(data.context);
  101. data
  102. .process(function() {
  103. return $this.fileupload('process', data);
  104. })
  105. .always(function() {
  106. data.context
  107. .each(function(index) {
  108. $(this)
  109. .find('.size')
  110. .text(that._formatFileSize(data.files[index].size));
  111. })
  112. .removeClass('processing');
  113. that._renderPreviews(data);
  114. })
  115. .done(function() {
  116. data.context.find('.start').prop('disabled', false);
  117. if (
  118. that._trigger('added', e, data) !== false &&
  119. (options.autoUpload || data.autoUpload) &&
  120. data.autoUpload !== false
  121. ) {
  122. data.submit();
  123. }
  124. })
  125. .fail(function() {
  126. if (data.files.error) {
  127. data.context.each(function(index) {
  128. var error = data.files[index].error;
  129. if (error) {
  130. $(this)
  131. .find('.error')
  132. .text(error);
  133. }
  134. });
  135. }
  136. });
  137. },
  138. // Callback for the start of each file upload request:
  139. send: function(e, data) {
  140. if (e.isDefaultPrevented()) {
  141. return false;
  142. }
  143. var that =
  144. $(this).data('blueimp-fileupload') || $(this).data('fileupload');
  145. if (
  146. data.context &&
  147. data.dataType &&
  148. data.dataType.substr(0, 6) === 'iframe'
  149. ) {
  150. // Iframe Transport does not support progress events.
  151. // In lack of an indeterminate progress bar, we set
  152. // the progress to 100%, showing the full animated bar:
  153. data.context
  154. .find('.progress')
  155. .addClass(!$.support.transition && 'progress-animated')
  156. .attr('aria-valuenow', 100)
  157. .children()
  158. .first()
  159. .css('width', '100%');
  160. }
  161. return that._trigger('sent', e, data);
  162. },
  163. // Callback for successful uploads:
  164. done: function(e, data) {
  165. if (e.isDefaultPrevented()) {
  166. return false;
  167. }
  168. var that =
  169. $(this).data('blueimp-fileupload') || $(this).data('fileupload'),
  170. getFilesFromResponse =
  171. data.getFilesFromResponse || that.options.getFilesFromResponse,
  172. files = getFilesFromResponse(data),
  173. template,
  174. deferred;
  175. if (data.context) {
  176. data.context.each(function(index) {
  177. var file = files[index] || { error: 'Empty file upload result' };
  178. deferred = that._addFinishedDeferreds();
  179. that._transition($(this)).done(function() {
  180. var node = $(this);
  181. template = that._renderDownload([file]).replaceAll(node);
  182. that._forceReflow(template);
  183. that._transition(template).done(function() {
  184. data.context = $(this);
  185. that._trigger('completed', e, data);
  186. that._trigger('finished', e, data);
  187. deferred.resolve();
  188. });
  189. });
  190. });
  191. } else {
  192. template = that
  193. ._renderDownload(files)
  194. [that.options.prependFiles ? 'prependTo' : 'appendTo'](
  195. that.options.filesContainer
  196. );
  197. that._forceReflow(template);
  198. deferred = that._addFinishedDeferreds();
  199. that._transition(template).done(function() {
  200. data.context = $(this);
  201. that._trigger('completed', e, data);
  202. that._trigger('finished', e, data);
  203. deferred.resolve();
  204. });
  205. }
  206. },
  207. // Callback for failed (abort or error) uploads:
  208. fail: function(e, data) {
  209. if (e.isDefaultPrevented()) {
  210. return false;
  211. }
  212. var that =
  213. $(this).data('blueimp-fileupload') || $(this).data('fileupload'),
  214. template,
  215. deferred;
  216. if (data.context) {
  217. data.context.each(function(index) {
  218. if (data.errorThrown !== 'abort') {
  219. var file = data.files[index];
  220. file.error =
  221. file.error || data.errorThrown || data.i18n('unknownError');
  222. deferred = that._addFinishedDeferreds();
  223. that._transition($(this)).done(function() {
  224. var node = $(this);
  225. template = that._renderDownload([file]).replaceAll(node);
  226. that._forceReflow(template);
  227. that._transition(template).done(function() {
  228. data.context = $(this);
  229. that._trigger('failed', e, data);
  230. that._trigger('finished', e, data);
  231. deferred.resolve();
  232. });
  233. });
  234. } else {
  235. deferred = that._addFinishedDeferreds();
  236. that._transition($(this)).done(function() {
  237. $(this).remove();
  238. that._trigger('failed', e, data);
  239. that._trigger('finished', e, data);
  240. deferred.resolve();
  241. });
  242. }
  243. });
  244. } else if (data.errorThrown !== 'abort') {
  245. data.context = that
  246. ._renderUpload(data.files)
  247. [that.options.prependFiles ? 'prependTo' : 'appendTo'](
  248. that.options.filesContainer
  249. )
  250. .data('data', data);
  251. that._forceReflow(data.context);
  252. deferred = that._addFinishedDeferreds();
  253. that._transition(data.context).done(function() {
  254. data.context = $(this);
  255. that._trigger('failed', e, data);
  256. that._trigger('finished', e, data);
  257. deferred.resolve();
  258. });
  259. } else {
  260. that._trigger('failed', e, data);
  261. that._trigger('finished', e, data);
  262. that._addFinishedDeferreds().resolve();
  263. }
  264. },
  265. // Callback for upload progress events:
  266. progress: function(e, data) {
  267. if (e.isDefaultPrevented()) {
  268. return false;
  269. }
  270. var progress = Math.floor((data.loaded / data.total) * 100);
  271. if (data.context) {
  272. data.context.each(function() {
  273. $(this)
  274. .find('.progress')
  275. .attr('aria-valuenow', progress)
  276. .children()
  277. .first()
  278. .css('width', progress + '%');
  279. });
  280. }
  281. },
  282. // Callback for global upload progress events:
  283. progressall: function(e, data) {
  284. if (e.isDefaultPrevented()) {
  285. return false;
  286. }
  287. var $this = $(this),
  288. progress = Math.floor((data.loaded / data.total) * 100),
  289. globalProgressNode = $this.find('.fileupload-progress'),
  290. extendedProgressNode = globalProgressNode.find('.progress-extended');
  291. if (extendedProgressNode.length) {
  292. extendedProgressNode.html(
  293. (
  294. $this.data('blueimp-fileupload') || $this.data('fileupload')
  295. )._renderExtendedProgress(data)
  296. );
  297. }
  298. globalProgressNode
  299. .find('.progress')
  300. .attr('aria-valuenow', progress)
  301. .children()
  302. .first()
  303. .css('width', progress + '%');
  304. },
  305. // Callback for uploads start, equivalent to the global ajaxStart event:
  306. start: function(e) {
  307. if (e.isDefaultPrevented()) {
  308. return false;
  309. }
  310. var that =
  311. $(this).data('blueimp-fileupload') || $(this).data('fileupload');
  312. that._resetFinishedDeferreds();
  313. that._transition($(this).find('.fileupload-progress')).done(function() {
  314. that._trigger('started', e);
  315. });
  316. },
  317. // Callback for uploads stop, equivalent to the global ajaxStop event:
  318. stop: function(e) {
  319. if (e.isDefaultPrevented()) {
  320. return false;
  321. }
  322. var that =
  323. $(this).data('blueimp-fileupload') || $(this).data('fileupload'),
  324. deferred = that._addFinishedDeferreds();
  325. $.when.apply($, that._getFinishedDeferreds()).done(function() {
  326. that._trigger('stopped', e);
  327. });
  328. that._transition($(this).find('.fileupload-progress')).done(function() {
  329. $(this)
  330. .find('.progress')
  331. .attr('aria-valuenow', '0')
  332. .children()
  333. .first()
  334. .css('width', '0%');
  335. $(this)
  336. .find('.progress-extended')
  337. .html(' ');
  338. deferred.resolve();
  339. });
  340. },
  341. processstart: function(e) {
  342. if (e.isDefaultPrevented()) {
  343. return false;
  344. }
  345. $(this).addClass('fileupload-processing');
  346. },
  347. processstop: function(e) {
  348. if (e.isDefaultPrevented()) {
  349. return false;
  350. }
  351. $(this).removeClass('fileupload-processing');
  352. },
  353. // Callback for file deletion:
  354. destroy: function(e, data) {
  355. if (e.isDefaultPrevented()) {
  356. return false;
  357. }
  358. var that =
  359. $(this).data('blueimp-fileupload') || $(this).data('fileupload'),
  360. removeNode = function() {
  361. that._transition(data.context).done(function() {
  362. $(this).remove();
  363. that._trigger('destroyed', e, data);
  364. });
  365. };
  366. if (data.url) {
  367. data.dataType = data.dataType || that.options.dataType;
  368. $.ajax(data)
  369. .done(removeNode)
  370. .fail(function() {
  371. that._trigger('destroyfailed', e, data);
  372. });
  373. } else {
  374. removeNode();
  375. }
  376. }
  377. },
  378. _resetFinishedDeferreds: function() {
  379. this._finishedUploads = [];
  380. },
  381. _addFinishedDeferreds: function(deferred) {
  382. // eslint-disable-next-line new-cap
  383. var promise = deferred || $.Deferred();
  384. this._finishedUploads.push(promise);
  385. return promise;
  386. },
  387. _getFinishedDeferreds: function() {
  388. return this._finishedUploads;
  389. },
  390. // Link handler, that allows to download files
  391. // by drag & drop of the links to the desktop:
  392. _enableDragToDesktop: function() {
  393. var link = $(this),
  394. url = link.prop('href'),
  395. name = link.prop('download'),
  396. type = 'application/octet-stream';
  397. link.bind('dragstart', function(e) {
  398. try {
  399. e.originalEvent.dataTransfer.setData(
  400. 'DownloadURL',
  401. [type, name, url].join(':')
  402. );
  403. } catch (ignore) {
  404. // Ignore exceptions
  405. }
  406. });
  407. },
  408. _formatFileSize: function(bytes) {
  409. if (typeof bytes !== 'number') {
  410. return '';
  411. }
  412. if (bytes >= 1000000000) {
  413. return (bytes / 1000000000).toFixed(2) + ' GB';
  414. }
  415. if (bytes >= 1000000) {
  416. return (bytes / 1000000).toFixed(2) + ' MB';
  417. }
  418. return (bytes / 1000).toFixed(2) + ' KB';
  419. },
  420. _formatBitrate: function(bits) {
  421. if (typeof bits !== 'number') {
  422. return '';
  423. }
  424. if (bits >= 1000000000) {
  425. return (bits / 1000000000).toFixed(2) + ' Gbit/s';
  426. }
  427. if (bits >= 1000000) {
  428. return (bits / 1000000).toFixed(2) + ' Mbit/s';
  429. }
  430. if (bits >= 1000) {
  431. return (bits / 1000).toFixed(2) + ' kbit/s';
  432. }
  433. return bits.toFixed(2) + ' bit/s';
  434. },
  435. _formatTime: function(seconds) {
  436. var date = new Date(seconds * 1000),
  437. days = Math.floor(seconds / 86400);
  438. days = days ? days + 'd ' : '';
  439. return (
  440. days +
  441. ('0' + date.getUTCHours()).slice(-2) +
  442. ':' +
  443. ('0' + date.getUTCMinutes()).slice(-2) +
  444. ':' +
  445. ('0' + date.getUTCSeconds()).slice(-2)
  446. );
  447. },
  448. _formatPercentage: function(floatValue) {
  449. return (floatValue * 100).toFixed(2) + ' %';
  450. },
  451. _renderExtendedProgress: function(data) {
  452. return (
  453. this._formatBitrate(data.bitrate) +
  454. ' | ' +
  455. this._formatTime(((data.total - data.loaded) * 8) / data.bitrate) +
  456. ' | ' +
  457. this._formatPercentage(data.loaded / data.total) +
  458. ' | ' +
  459. this._formatFileSize(data.loaded) +
  460. ' / ' +
  461. this._formatFileSize(data.total)
  462. );
  463. },
  464. _renderTemplate: function(func, files) {
  465. if (!func) {
  466. return $();
  467. }
  468. var result = func({
  469. files: files,
  470. formatFileSize: this._formatFileSize,
  471. options: this.options
  472. });
  473. if (result instanceof $) {
  474. return result;
  475. }
  476. return $(this.options.templatesContainer)
  477. .html(result)
  478. .children();
  479. },
  480. _renderPreviews: function(data) {
  481. data.context.find('.preview').each(function(index, elm) {
  482. $(elm).append(data.files[index].preview);
  483. });
  484. },
  485. _renderUpload: function(files) {
  486. return this._renderTemplate(this.options.uploadTemplate, files);
  487. },
  488. _renderDownload: function(files) {
  489. return this._renderTemplate(this.options.downloadTemplate, files)
  490. .find('a[download]')
  491. .each(this._enableDragToDesktop)
  492. .end();
  493. },
  494. _startHandler: function(e) {
  495. e.preventDefault();
  496. var button = $(e.currentTarget),
  497. template = button.closest('.template-upload'),
  498. data = template.data('data');
  499. button.prop('disabled', true);
  500. if (data && data.submit) {
  501. data.submit();
  502. }
  503. },
  504. _cancelHandler: function(e) {
  505. e.preventDefault();
  506. var template = $(e.currentTarget).closest(
  507. '.template-upload,.template-download'
  508. ),
  509. data = template.data('data') || {};
  510. data.context = data.context || template;
  511. if (data.abort) {
  512. data.abort();
  513. } else {
  514. data.errorThrown = 'abort';
  515. this._trigger('fail', e, data);
  516. }
  517. },
  518. _deleteHandler: function(e) {
  519. e.preventDefault();
  520. var button = $(e.currentTarget);
  521. this._trigger(
  522. 'destroy',
  523. e,
  524. $.extend(
  525. {
  526. context: button.closest('.template-download'),
  527. type: 'DELETE'
  528. },
  529. button.data()
  530. )
  531. );
  532. },
  533. _forceReflow: function(node) {
  534. return $.support.transition && node.length && node[0].offsetWidth;
  535. },
  536. _transition: function(node) {
  537. // eslint-disable-next-line new-cap
  538. var dfd = $.Deferred();
  539. if (
  540. $.support.transition &&
  541. node.hasClass('fade') &&
  542. node.is(':visible')
  543. ) {
  544. node
  545. .bind($.support.transition.end, function(e) {
  546. // Make sure we don't respond to other transitions events
  547. // in the container element, e.g. from button elements:
  548. if (e.target === node[0]) {
  549. node.unbind($.support.transition.end);
  550. dfd.resolveWith(node);
  551. }
  552. })
  553. .toggleClass('in');
  554. } else {
  555. node.toggleClass('in');
  556. dfd.resolveWith(node);
  557. }
  558. return dfd;
  559. },
  560. _initButtonBarEventHandlers: function() {
  561. var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
  562. filesList = this.options.filesContainer;
  563. this._on(fileUploadButtonBar.find('.start'), {
  564. click: function(e) {
  565. e.preventDefault();
  566. filesList.find('.start').click();
  567. }
  568. });
  569. this._on(fileUploadButtonBar.find('.cancel'), {
  570. click: function(e) {
  571. e.preventDefault();
  572. filesList.find('.cancel').click();
  573. }
  574. });
  575. this._on(fileUploadButtonBar.find('.delete'), {
  576. click: function(e) {
  577. e.preventDefault();
  578. filesList
  579. .find('.toggle:checked')
  580. .closest('.template-download')
  581. .find('.delete')
  582. .click();
  583. fileUploadButtonBar.find('.toggle').prop('checked', false);
  584. }
  585. });
  586. this._on(fileUploadButtonBar.find('.toggle'), {
  587. change: function(e) {
  588. filesList
  589. .find('.toggle')
  590. .prop('checked', $(e.currentTarget).is(':checked'));
  591. }
  592. });
  593. },
  594. _destroyButtonBarEventHandlers: function() {
  595. this._off(
  596. this.element
  597. .find('.fileupload-buttonbar')
  598. .find('.start, .cancel, .delete'),
  599. 'click'
  600. );
  601. this._off(this.element.find('.fileupload-buttonbar .toggle'), 'change.');
  602. },
  603. _initEventHandlers: function() {
  604. this._super();
  605. this._on(this.options.filesContainer, {
  606. 'click .start': this._startHandler,
  607. 'click .cancel': this._cancelHandler,
  608. 'click .delete': this._deleteHandler
  609. });
  610. this._initButtonBarEventHandlers();
  611. },
  612. _destroyEventHandlers: function() {
  613. this._destroyButtonBarEventHandlers();
  614. this._off(this.options.filesContainer, 'click');
  615. this._super();
  616. },
  617. _enableFileInputButton: function() {
  618. this.element
  619. .find('.fileinput-button input')
  620. .prop('disabled', false)
  621. .parent()
  622. .removeClass('disabled');
  623. },
  624. _disableFileInputButton: function() {
  625. this.element
  626. .find('.fileinput-button input')
  627. .prop('disabled', true)
  628. .parent()
  629. .addClass('disabled');
  630. },
  631. _initTemplates: function() {
  632. var options = this.options;
  633. options.templatesContainer = this.document[0].createElement(
  634. options.filesContainer.prop('nodeName')
  635. );
  636. if (tmpl) {
  637. if (options.uploadTemplateId) {
  638. options.uploadTemplate = tmpl(options.uploadTemplateId);
  639. }
  640. if (options.downloadTemplateId) {
  641. options.downloadTemplate = tmpl(options.downloadTemplateId);
  642. }
  643. }
  644. },
  645. _initFilesContainer: function() {
  646. var options = this.options;
  647. if (options.filesContainer === undefined) {
  648. options.filesContainer = this.element.find('.files');
  649. } else if (!(options.filesContainer instanceof $)) {
  650. options.filesContainer = $(options.filesContainer);
  651. }
  652. },
  653. _initSpecialOptions: function() {
  654. this._super();
  655. this._initFilesContainer();
  656. this._initTemplates();
  657. },
  658. _create: function() {
  659. this._super();
  660. this._resetFinishedDeferreds();
  661. if (!$.support.fileInput) {
  662. this._disableFileInputButton();
  663. }
  664. },
  665. enable: function() {
  666. var wasDisabled = false;
  667. if (this.options.disabled) {
  668. wasDisabled = true;
  669. }
  670. this._super();
  671. if (wasDisabled) {
  672. this.element.find('input, button').prop('disabled', false);
  673. this._enableFileInputButton();
  674. }
  675. },
  676. disable: function() {
  677. if (!this.options.disabled) {
  678. this.element.find('input, button').prop('disabled', true);
  679. this._disableFileInputButton();
  680. }
  681. this._super();
  682. }
  683. });
  684. });