download-zip-file.html 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. ---
  2. title: "Download the generated zip file"
  3. layout: default
  4. section: example
  5. ---
  6. <p>Tip : check the source of the page !</p>
  7. <h2>The FileSaver API</h2>
  8. <div>
  9. Works on firefox, chrome , opera &gt;= 15 and IE &gt;= 10 (but NOT in compatibility view).<br/>
  10. <button id="blob" class="btn btn-primary">click to download</button>
  11. </div>
  12. <h2>The data URL</h2>
  13. <div>
  14. Does not work in IE, has restrictions on the length.<br/>
  15. <button id="data_uri" class="btn btn-primary">click to download</button>
  16. </div>
  17. <script type="text/javascript">
  18. (function () {
  19. var zip = new JSZip();
  20. zip.file("Hello.txt", "Hello world\n");
  21. function bindEvent(el, eventName, eventHandler) {
  22. if (el.addEventListener){
  23. // standard way
  24. el.addEventListener(eventName, eventHandler, false);
  25. } else if (el.attachEvent){
  26. // old IE
  27. el.attachEvent('on'+eventName, eventHandler);
  28. }
  29. }
  30. // Blob
  31. var blobLink = document.getElementById('blob');
  32. if (JSZip.support.blob) {
  33. function downloadWithBlob() {
  34. try {
  35. var blob = zip.generate({type:"blob"});
  36. // see FileSaver.js
  37. saveAs(blob, "hello.zip");
  38. } catch(e) {
  39. blobLink.innerHTML += " " + e;
  40. }
  41. return false;
  42. }
  43. bindEvent(blobLink, 'click', downloadWithBlob);
  44. } else {
  45. blobLink.innerHTML += " (not supported on this browser)";
  46. }
  47. // data URI
  48. function downloadWithDataURI() {
  49. window.location = "data:application/zip;base64," + zip.generate({type:"base64"});
  50. }
  51. var dataUriLink = document.getElementById('data_uri');
  52. bindEvent(dataUriLink, 'click', downloadWithDataURI);
  53. })();
  54. </script>