下载接口
接口是一个post请求,返回的是一个文件流。
配置 axios
响应拦截
httpRequest.interceptors.response.use(function(response) {
const headers = response.headers
// 文件下载
if (headers['content-type'] === 'application/vnd.ms-excel' || headers['content-disposition']) {
return response
}
});
配置接口:
添加:responseType: ‘blob’
export function classAttendanceDetailExport(data) {
return httpRequest({
method: 'post',
url: "/mgr/report/classAttendanceDetail/export",
data: data,
responseType: 'blob'
});
}
下载功能:
/**
* 导出表格
*/
async exportTable() {
try {
const res = await httpRequest.classAttendanceDetailExport({
classId: this.row.classId,
groupId: this.row.groupId,
});
const filename = `课程到课统计${forMatDate(new Date(),'yyyyMMddhhmmss')}`;
handleFileStreamDownload(res,filename,'.xls');
} catch (error) {
console.log("导出表格-出错了", error)
}
},
/**
* 下载文件
* @param {*} res
* @param {*} filename 文件名
* @param {*} format 文件格式
* @returns
*/
export function handleFileStreamDownload(res,filename,format){
if (!res) {
return
}
if (window.navigator.msSaveBlob) { // IE以及IE内核的浏览器
try {
window.navigator.msSaveBlob(res.data, `${filename}${format}`)
} catch (e) {
console.log(e)
}
} else {
let url = window.URL.createObjectURL(new Blob([res.data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', `${filename}${format}`)// 文件名
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // 下载完成移除元素
window.URL.revokeObjectURL(url) // 释放掉blob对象
}
}