下载文件,无非以下几种方式:
第一种:后端直接返回文件url地址
window.location.href = url
第二种:后端返回二进制文件流地址
我们先来看看后端返回的二进制文件流长什么样子:
是一堆的乱码。。。
那如何解决乱码???在ajax请求前通过设置responseType:‘blob’转化为blob对象
在设置responseType:‘blob’以后,我们在看下接口会返回什么样的内容尼:
上面图片看出,返回了blob对象!!!
解决思路来了:前端通过创建a标签,为href属性赋值,模拟自动点击事件,最后在清除a标签即可,使用到URL.createObjectURL(object)这个方法
可查阅URL.createObjectURL(object); 返回url对象
// get 请求
axios({
method: 'get',
url, // 这里自行设置传参
params, // 这里自行设置传参
responseType:'blob' // 这里是重点,敲黑板
}).then(res => {
if(res.data.size > 0 === 2000){
let elink = document.createElement('a');
document.body.appendChild(elink);
elink.style.display = 'none'; // 隐藏起来
elink.download = 'XXX文件.pdf'; // 设置下载文件的名称
let blob = new Blob([res.data]);
elink.href = Window.URL.createObjectURL(blob) // 通过createObjectURL方法转换成对象url
elink.click();
document.body.removeChild(elink);
URL.revokeObjectURL(elink.href); // 释放URL 对象
}
})
这里还有:
该文章中通过设置responseType:arraybuffer,展示出图片。