download.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. //download.js v4.2, by dandavis; 2008-2016. [MIT] see http://danml.com/download.html for tests/usage
  2. // v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
  3. // v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
  4. // v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
  5. // v4 adds AMD/UMD, commonJS, and plain browser support
  6. // v4.1 adds url download capability via solo URL argument (same domain/CORS only)
  7. // v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
  8. // https://github.com/rndme/download
  9. export default function download(data, strFileName, strMimeType) {
  10. let self = window, // this script is only for browsers anyway...
  11. defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
  12. mimeType = strMimeType || defaultMime,
  13. payload = data,
  14. url = !strFileName && !strMimeType && payload,
  15. anchor = document.createElement("a"),
  16. toString = function(a) { return String(a); },
  17. myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
  18. fileName = strFileName || "download",
  19. blob,
  20. reader;
  21. myBlob = myBlob.call ? myBlob.bind(self) : Blob;
  22. if (String(this) === "true") { //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
  23. payload = [payload, mimeType];
  24. mimeType = payload[0];
  25. payload = payload[1];
  26. }
  27. if (url && url.length < 2048) { // if no filename and no mime, assume a url was passed as the only argument
  28. fileName = url.split("/").pop().split("?")[0];
  29. anchor.href = url; // assign href prop to temp anchor
  30. if (anchor.href.indexOf(url) !== -1) { // if the browser determines that it's a potentially valid url path:
  31. let ajax = new XMLHttpRequest();
  32. ajax.open("GET", url, true);
  33. ajax.responseType = 'blob';
  34. ajax.onload = function(e) {
  35. download(e.target.response, fileName, defaultMime);
  36. };
  37. setTimeout(function() { ajax.send(); }, 0); // allows setting custom ajax headers using the return:
  38. return ajax;
  39. } // end if valid url?
  40. } // end if url?
  41. //go ahead and download dataURLs right away
  42. if (/^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(payload)) {
  43. if (payload.length > (1024 * 1024 * 1.999) && myBlob !== toString) {
  44. payload = dataUrlToBlob(payload);
  45. mimeType = payload.type || defaultMime;
  46. } else {
  47. return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
  48. navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
  49. saver(payload); // everyone else can save dataURLs un-processed
  50. }
  51. } else { //not data url, is it a string with special needs?
  52. if (/([\x80-\xff])/.test(payload)) {
  53. let i = 0,
  54. tempUiArr = new Uint8Array(payload.length),
  55. mx = tempUiArr.length;
  56. for (i; i < mx; ++i) tempUiArr[i] = payload.charCodeAt(i);
  57. payload = new myBlob([tempUiArr], { type: mimeType });
  58. }
  59. }
  60. blob = payload instanceof myBlob ?
  61. payload :
  62. new myBlob([payload], { type: mimeType });
  63. function dataUrlToBlob(strUrl) {
  64. let parts = strUrl.split(/[:;,]/),
  65. type = parts[1],
  66. decoder = parts[2] == "base64" ? atob : decodeURIComponent,
  67. binData = decoder(parts.pop()),
  68. mx = binData.length,
  69. i = 0,
  70. uiArr = new Uint8Array(mx);
  71. for (i; i < mx; ++i) uiArr[i] = binData.charCodeAt(i);
  72. return new myBlob([uiArr], { type: type });
  73. }
  74. function saver(url, winMode) {
  75. if ('download' in anchor) { //html5 A[download]
  76. anchor.href = url;
  77. anchor.setAttribute("download", fileName);
  78. anchor.className = "download-js-link";
  79. anchor.innerHTML = "downloading...";
  80. anchor.style.display = "none";
  81. document.body.appendChild(anchor);
  82. setTimeout(function() {
  83. anchor.click();
  84. document.body.removeChild(anchor);
  85. if (winMode === true) { setTimeout(function() { self.URL.revokeObjectURL(anchor.href); }, 250); }
  86. }, 66);
  87. return true;
  88. }
  89. // handle non-a[download] safari as best we can:
  90. if (/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
  91. if (/^data:/.test(url)) url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
  92. if (!window.open(url)) { // popup blocked, offer direct download:
  93. if (confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")) { location.href = url; }
  94. }
  95. return true;
  96. }
  97. //do iframe dataURL download (old ch+FF):
  98. let f = document.createElement("iframe");
  99. document.body.appendChild(f);
  100. if (!winMode && /^data:/.test(url)) { // force a mime that will download:
  101. url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
  102. }
  103. f.src = url;
  104. setTimeout(function() { document.body.removeChild(f); }, 333);
  105. } //end saver
  106. if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
  107. return navigator.msSaveBlob(blob, fileName);
  108. }
  109. if (self.URL) { // simple fast and modern way using Blob and URL:
  110. saver(self.URL.createObjectURL(blob), true);
  111. } else {
  112. // handle non-Blob()+non-URL browsers:
  113. if (typeof blob === "string" || blob.constructor === toString) {
  114. try {
  115. return saver("data:" + mimeType + ";base64," + self.btoa(blob));
  116. } catch (y) {
  117. return saver("data:" + mimeType + "," + encodeURIComponent(blob));
  118. }
  119. }
  120. // Blob but not URL support:
  121. reader = new FileReader();
  122. reader.onload = function(e) {
  123. saver(this.result);
  124. };
  125. reader.readAsDataURL(blob);
  126. }
  127. return true;
  128. }; /* end download() */