post 请求
export default function (data) {
axios({
method: 'post',
url: data.url, //后端接口地址
responseType: 'blob', //bolb格式的请求方式
headers: {
Authentication: getToken('Admin-Token') //请求头
},
data: data.data //需要传给后端的请求参数体
}).then(res => {
const BLOB = res.data;
const fileReader = new FileReader();
fileReader.readAsDataURL(BLOB); //对请求返回的文件进行处理
fileReader.onload = (e) => {
let a = document.createElement('a');
a.download = data.name + '.xlsx'
a.href = e.target.result;
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
}
}).catch(err => {
console.log(err.message)
})
}
get 请求
export default function (data) {
axios({
url: data.url,
method: 'get',
responseType: 'blob',
params: data.data, //与post传参方式不同之处
headers: {
Authentication: getToken()
}
}).then(res => {
var blob = new Blob([res.data],
{type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
var filename = data.name + '.xlsx';
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.style.display = 'none';
downloadElement.href = href;
downloadElement.download =filename ; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
}
}
网友评论