download.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. var 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. var 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. var i=0, tempUiArr= new Uint8Array(payload.length), mx=tempUiArr.length;
  54. for(i;i<mx;++i) tempUiArr[i]= payload.charCodeAt(i);
  55. payload=new myBlob([tempUiArr], {type: mimeType});
  56. }
  57. }
  58. blob = payload instanceof myBlob ?
  59. payload :
  60. new myBlob([payload], {type: mimeType}) ;
  61. function dataUrlToBlob(strUrl) {
  62. var parts= strUrl.split(/[:;,]/),
  63. type= parts[1],
  64. decoder= parts[2] == "base64" ? atob : decodeURIComponent,
  65. binData= decoder( parts.pop() ),
  66. mx= binData.length,
  67. i= 0,
  68. uiArr= new Uint8Array(mx);
  69. for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
  70. return new myBlob([uiArr], {type: type});
  71. }
  72. function saver(url, winMode){
  73. if ('download' in anchor) { //html5 A[download]
  74. anchor.href = url;
  75. anchor.setAttribute("download", fileName);
  76. anchor.className = "download-js-link";
  77. anchor.innerHTML = "downloading...";
  78. anchor.style.display = "none";
  79. document.body.appendChild(anchor);
  80. setTimeout(function() {
  81. anchor.click();
  82. document.body.removeChild(anchor);
  83. if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
  84. }, 66);
  85. return true;
  86. }
  87. // handle non-a[download] safari as best we can:
  88. if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
  89. if(/^data:/.test(url)) url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
  90. if(!window.open(url)){ // popup blocked, offer direct download:
  91. if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
  92. }
  93. return true;
  94. }
  95. //do iframe dataURL download (old ch+FF):
  96. var f = document.createElement("iframe");
  97. document.body.appendChild(f);
  98. if(!winMode && /^data:/.test(url)){ // force a mime that will download:
  99. url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
  100. }
  101. f.src=url;
  102. setTimeout(function(){ document.body.removeChild(f); }, 333);
  103. }//end saver
  104. if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
  105. return navigator.msSaveBlob(blob, fileName);
  106. }
  107. if(self.URL){ // simple fast and modern way using Blob and URL:
  108. saver(self.URL.createObjectURL(blob), true);
  109. }else{
  110. // handle non-Blob()+non-URL browsers:
  111. if(typeof blob === "string" || blob.constructor===toString ){
  112. try{
  113. return saver( "data:" + mimeType + ";base64," + self.btoa(blob) );
  114. }catch(y){
  115. return saver( "data:" + mimeType + "," + encodeURIComponent(blob) );
  116. }
  117. }
  118. // Blob but not URL support:
  119. reader=new FileReader();
  120. reader.onload=function(e){
  121. saver(this.result);
  122. };
  123. reader.readAsDataURL(blob);
  124. }
  125. return true;
  126. }; /* end download() */