前端JS下载文件总结
阅读原文时间:2023年07月10日阅读:2

Data URLs: 即前缀为data: 协议的URL,其允许内容创建者向文档中嵌入小文件。

  例如:可以直接在HTML中的img元素直接使用Data URLs ;

data:[][;base64],

  • mediatype: 是个 MIME 类型的字符串,例如 "image/jpeg" 表示 JPEG 图像文件,'text/plain' 则表示txt文件,"excel/plain" 则表示excel文件;如果被省略,则默认值为 text/plain;charset=US-ASCII。
  • base64:即是base64编码,如果data是文本格式,可以直接嵌入文本。如下:

data:,Hello%2C%20World!  // text/plain 类型数据
data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D  // base64 编码版本

  如果是二进制数据,可以进行base64编码之后再进行嵌入。在JavaScript中,有两个函数btoa()atob()分别用于解码和编码base64字符串。

Blob 对象表示一个不可变、原始数据的类文件对象,其中Blob.size代表对象中所包含数据的大小(字节),Blob.type 表明该Blob对象所包含数据的 MIME 类型。

  其方法主要是blob.arrayBuffer()返回一个promise且包含blob所有内容的二进制格式的ArrayBuffer。

// 可以直接创建一个简单的文本Blob对象
new Blob(["hello world"]) 
// 一个包含DOMString的数组,然后创建一个HTML类型的Blob对象
new Blob(["hello world".bold()], {type : 'text/html'});

  了解了上面的概念之后,步入正题

  1. 最简单的方式,比如下载图片,可以让后端以附件的形式下载,加以下面代码downloadSimple()方法,就可以下载图片文件了。

  downloadSimple(url: string, fileName: string) {
 const anchor = document.createElement('a');
const fileName = fileName || 'download';
if ('download' in anchor) { //html5 A[download]
anchor.href = url;
anchor.setAttribute("download", fileName);
anchor.className = "download-js-link";
anchor.innerHTML = "downloading…";
anchor.style.display = "none";
document.body.appendChild(anchor);
setTimeout(function () {
anchor.click();
document.body.removeChild(anchor);
}, 66);
return true;
}
 }

  2.GET请求下载,且responseType为blob。代码如下:(Get方法长度限制最大不要超过2048,即2048+35。这里要解释一下,其实get方法并没有限制URL最大长度限制,是浏览器的限制要求,而这个2083就是IE浏览器限制的最大长度,也是各个浏览器当中最小)。

 if (url && url.length < 2048) {
fileName = url.split("/").pop().split("?")[0];
anchor.href = url;
if (anchor.href.indexOf(url) !== -1) {
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.responseType = 'blob';
ajax.onload = function (e:any) {
_this.downloadSimple(e.target.response, fileName); // 调用上面的a标签式下载方法
};
setTimeout(function () { ajax.send(); }, 0);
return ajax;
}
}

  3.POST方式下载,且后端返回base64编码格式的数据流,类似于这种(ZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==),然后可以拼接成Data URLs格式,用以上的代码段downloadSimple()就可以直接下载文件,如果是下载excel文件,则Data URLs的参数mediatype为"excel/plain" 。

  但是如果是IE浏览器用这种代码不行,可以用navigator.msSaveBlob()方法下载一个Blob 对象。首先需要把Data URLs转换成可供浏览器下载的Blob 对象。方法如下:

function dataUrlToBlob(strUrl: string) {  
  var parts = strUrl.split(/\[:;,\]/),  
    type = parts\[1\],  
    decoder = parts\[2\] == "base64" ? atob : decodeURIComponent,  
    binData = decoder(parts.pop()),  
    mx = binData.length,  
    i = 0,  
    uiArr = new Uint8Array(mx);

  for (i; i < mx; ++i) uiArr\[i\] = binData.charCodeAt(i);

  return new myBlob(\[uiArr\], { type: type });  
}  

  navigator.msSaveBlob(dataUrlToBlob(url));