download.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. (function(root, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. // AMD. Register as an anonymous module.
  4. define([], factory);
  5. } else if (typeof exports === 'object') {
  6. // Node. Does not work with strict CommonJS, but
  7. // only CommonJS-like environments that support module.exports,
  8. // like Node.
  9. module.exports = factory();
  10. } else {
  11. // Browser globals (root is window)
  12. root.download = factory();
  13. }
  14. }(this, function() {
  15. return function download(data, strFileName, strMimeType) {
  16. var self = window, // this script is only for browsers anyway...
  17. defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
  18. mimeType = strMimeType || defaultMime,
  19. payload = data,
  20. url = !strFileName && !strMimeType && payload,
  21. anchor = document.createElement("a"),
  22. toString = function(a) {
  23. return String(a);
  24. },
  25. myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
  26. fileName = strFileName || "download",
  27. blob,
  28. reader;
  29. myBlob = myBlob.call ? myBlob.bind(self) : Blob;
  30. if (String(this) ===
  31. "true") { //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
  32. payload = [payload, mimeType];
  33. mimeType = payload[0];
  34. payload = payload[1];
  35. }
  36. if (url && url.length <
  37. 2048) { // if no filename and no mime, assume a url was passed as the only argument
  38. fileName = url.split("/").pop().split("?")[0];
  39. anchor.href = url; // assign href prop to temp anchor
  40. if (anchor.href.indexOf(url) !== -
  41. 1) { // if the browser determines that it's a potentially valid url path:
  42. var ajax = new XMLHttpRequest();
  43. ajax.open("GET", url, true);
  44. ajax.responseType = 'blob';
  45. ajax.onload = function(e) {
  46. download(e.target.response, fileName, defaultMime);
  47. };
  48. setTimeout(function() {
  49. ajax.send();
  50. }, 0); // allows setting custom ajax headers using the return:
  51. return ajax;
  52. } // end if valid url?
  53. } // end if url?
  54. //go ahead and download dataURLs right away
  55. if (/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)) {
  56. if (payload.length > (1024 * 1024 * 1.999) && myBlob !== toString) {
  57. payload = dataUrlToBlob(payload);
  58. mimeType = payload.type || defaultMime;
  59. } else {
  60. return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
  61. navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
  62. saver(payload); // everyone else can save dataURLs un-processed
  63. }
  64. } //end if dataURL passed?
  65. blob = payload instanceof myBlob ?
  66. payload :
  67. new myBlob([payload], {
  68. type: mimeType
  69. });
  70. function dataUrlToBlob(strUrl) {
  71. var parts = strUrl.split(/[:;,]/),
  72. type = parts[1],
  73. decoder = parts[2] == "base64" ? atob : decodeURIComponent,
  74. binData = decoder(parts.pop()),
  75. mx = binData.length,
  76. i = 0,
  77. uiArr = new Uint8Array(mx);
  78. for (i; i < mx; ++i) uiArr[i] = binData.charCodeAt(i);
  79. return new myBlob([uiArr], {
  80. type: type
  81. });
  82. }
  83. function saver(url, winMode) {
  84. if ('download' in anchor) { //html5 A[download]
  85. anchor.href = url;
  86. anchor.setAttribute("download", fileName);
  87. anchor.className = "download-js-link";
  88. anchor.innerHTML = "downloading...";
  89. anchor.style.display = "none";
  90. document.body.appendChild(anchor);
  91. setTimeout(function() {
  92. anchor.click();
  93. document.body.removeChild(anchor);
  94. if (winMode === true) {
  95. setTimeout(function() {
  96. self.URL.revokeObjectURL(anchor.href);
  97. }, 250);
  98. }
  99. }, 66);
  100. return true;
  101. }
  102. // handle non-a[download] safari as best we can:
  103. if (/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
  104. url = url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
  105. if (!window.open(url)) { // popup blocked, offer direct download:
  106. if (confirm(
  107. "Displaying New Document\n\nUse Save As... to download, then click back to return to this page."
  108. )) {
  109. location.href = url;
  110. }
  111. }
  112. return true;
  113. }
  114. //do iframe dataURL download (old ch+FF):
  115. var f = document.createElement("iframe");
  116. document.body.appendChild(f);
  117. if (!winMode) { // force a mime that will download:
  118. url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
  119. }
  120. f.src = url;
  121. setTimeout(function() {
  122. document.body.removeChild(f);
  123. }, 333);
  124. } //end saver
  125. if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
  126. return navigator.msSaveBlob(blob, fileName);
  127. }
  128. if (self.URL) { // simple fast and modern way using Blob and URL:
  129. saver(self.URL.createObjectURL(blob), true);
  130. } else {
  131. // handle non-Blob()+non-URL browsers:
  132. if (typeof blob === "string" || blob.constructor === toString) {
  133. try {
  134. return saver("data:" + mimeType + ";base64," + self.btoa(blob));
  135. } catch (y) {
  136. return saver("data:" + mimeType + "," + encodeURIComponent(blob));
  137. }
  138. }
  139. // Blob but not URL support:
  140. reader = new FileReader();
  141. reader.onload = function(e) {
  142. saver(this.result);
  143. };
  144. reader.readAsDataURL(blob);
  145. }
  146. return true;
  147. }; /* end download() */
  148. }));