downloader.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. jQuery(function ($) {
  2. "use strict";
  3. /**
  4. * Reset the message.
  5. */
  6. function resetMessage () {
  7. $("#result")
  8. .removeClass()
  9. .text("");
  10. }
  11. /**
  12. * show a successful message.
  13. * @param {String} text the text to show.
  14. */
  15. function showMessage(text) {
  16. resetMessage();
  17. $("#result")
  18. .addClass("alert alert-success")
  19. .text(text);
  20. }
  21. /**
  22. * show an error message.
  23. * @param {String} text the text to show.
  24. */
  25. function showError(text) {
  26. resetMessage();
  27. $("#result")
  28. .addClass("alert alert-danger")
  29. .text(text);
  30. }
  31. /**
  32. * Fetch the content, add it to the JSZip object
  33. * and use a jQuery deferred to hold the result.
  34. * @param {String} url the url of the content to fetch.
  35. * @param {String} filename the filename to use in the JSZip object.
  36. * @param {JSZip} zip the JSZip instance.
  37. * @return {jQuery.Deferred} the deferred containing the data.
  38. */
  39. function deferredAddZip(url, filename, zip) {
  40. var deferred = $.Deferred();
  41. JSZipUtils.getBinaryContent(url, function (err, data) {
  42. if(err) {
  43. deferred.reject(err);
  44. } else {
  45. zip.file(filename, data, {binary:true});
  46. deferred.resolve(data);
  47. }
  48. });
  49. return deferred;
  50. }
  51. if(!JSZip.support.blob) {
  52. showError("This demo works only with a recent browser !");
  53. return;
  54. }
  55. var $form = $("#download_form").on("submit", function () {
  56. resetMessage();
  57. var zip = new JSZip();
  58. var deferreds = [];
  59. // find every checked item
  60. $(this).find(":checked").each(function () {
  61. var $this = $(this);
  62. var url = $this.data("url");
  63. var filename = url.replace(/.*\//g, "");
  64. deferreds.push(deferredAddZip(url, filename, zip));
  65. });
  66. // when everything has been downloaded, we can trigger the dl
  67. $.when.apply($, deferreds).done(function () {
  68. var blob = zip.generate({type:"blob"});
  69. // see FileSaver.js
  70. saveAs(blob, "example.zip");
  71. showMessage("done !");
  72. }).fail(function (err) {
  73. showError(err);
  74. });
  75. return false;
  76. });
  77. });
  78. // vim: set shiftwidth=4 softtabstop=4: