主要是在请求参数后面加上{responseType: 'blob'}或者arrayBuffer
this.$http.get(this.api.export, {
params: this.info,
// responseType: 'blob'
responseType: 'arraybuffer'
}).then(res => {
loading.close();
// 第一种
// let blob = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
// let objectUrl = URL.createObjectURL(blob);
// window.location.href = objectUrl; // 第二种
let fileName = res.headers['content-disposition'].split("=")[1].split(";")[0];
let objectUrl = URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.download = decodeURIComponent(fileName);
link.href = objectUrl;
link.click();
})
-----
1.有时候,前端页面上需要展示后台接口返回给我们的一个二进制文件,比如图片,那么我们应该如何下载呢
js中有个Blob对象,一个 Blob对象表示一个不可变的, 原始数据的类似文件对象。Blob表示的数据不一定是一个JavaScript原生格式 blob对象本质上是js中的一个对象,里面可以储存大量的二进制编码格式的数据。
2.创建Blob 对象
var debug = {hello: "world"};
var blob = new Blob(['后台返回的二进制文件'],{type : '该文件是什么类型的文件(MIME)'});
3.常用的文件类型有(MIME),根据需要返回怎样的文件,就填写怎样的MIME类型,也可以不写,写的话指定了下载的文件格式,不写,文件是什么格式,下载就是什么格式,根据项目需求.
后缀名 MIME名称
*.3gpp audio/3gpp, video/3gpp
*.ac3 audio/ac3
*.asf allpication/vnd.ms-asf
*.au audio/basic
*.css text/css
*.csv text/csv
*.doc application/msword
*.dot application/msword
*.dtd application/xml-dtd
*.dwg image/vnd.dwg
*.dxf image/vnd.dxf
*.gif image/gif
*.htm text/html
*.html text/html
*.jp2 image/jp2
*.jpe image/jpeg
*.jpeg image/jpeg
*.jpg image/jpeg
*.js text/javascript, application/javascript
*.json application/json
*.mp2 audio/mpeg, video/mpeg
*.mp3 audio/mpeg
*.mp4 audio/mp4, video/mp4
*.mpeg video/mpeg
*.mpg video/mpeg
*.mpp application/vnd.ms-project
*.ogg application/ogg, audio/ogg
*.pdf application/pdf
*.png image/png
*.pot application/vnd.ms-powerpoint
*.pps application/vnd.ms-powerpoint
*.ppt application/vnd.ms-powerpoint
*.rtf application/rtf, text/rtf
*.svf image/vnd.svf
*.tif image/tiff
*.tiff image/tiff
*.txt text/plain
*.wdb application/vnd.ms-works
*.wps application/vnd.ms-works
*.xhtml application/xhtml+xml
*.xlc application/vnd.ms-excel
*.xlm application/vnd.ms-excel
*.xls application/vnd.ms-excel
*.xlt application/vnd.ms-excel
*.xlw application/vnd.ms-excel
*.xml text/xml, application/xml
*.zip aplication/zip*.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet