1. 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)
})
}
2. 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对象
}
}
比较实用的写法 (导出xls)
async outImport () {
await this.$axios({
method: 'get',
url: 'logistics-order/excel',
params: this.params,
responseType: 'blob'
}).then((res) => {
// const binaryData = []
// binaryData.push(res.data)
// this.url = window.URL.createObjectURL(
// new Blob(binaryData, { type: 'application/vnd.ms-excel' })
// )
// window.open(this.url)
console.log(res)
let str = res.headers['content-disposition']
str = str.substr(str.indexOf('=') + 1, str.length)
console.log(str.split('.'))
this.downloadFile(res.data, decodeURI(str.split('.')[0] + '.xls'))
})
},
downloadFile (blob, fileName) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName)
} else {
const link = document.createElement('a')
const evt = document.createEvent('HTMLEvents')
evt.initEvent('click', false, false)
link.href = URL.createObjectURL(blob)
link.download = fileName
link.style.display = 'none'
document.body.appendChild(link)
link.click()
window.URL.revokeObjectURL(link.href)
}
}