请求接口:一定要加responseType: 'blob'
后端返回数据:
api.js
export function export() {
return request({
url: 'dev/api/export',
method: 'get',
responseType: 'blob',//一定要加
})
}
vue:
import {export} from '@/api'
// 导出
const exportTable = () => {
ElMessageBox.confirm('确定导出表格数据?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
})
.then(() => {
exportGradeScene().then((res) => {
exportFile(res)
})
})
.catch(() => {
ElMessage({
type: 'info',
message: '导出取消',
})
})
}
const exportFile = (response) => {
// 导出文件通用逻辑(仅限axios)
const contentDisposition = response.headers['content-disposition'] // 解析文件名
const filename = decodeURIComponent(
contentDisposition.split('filename=')[1].trim().replace(/\"/g, ''),
)
// 创建链接并触发下载
const url = window.URL.createObjectURL(
new Blob([response.data], {
type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}),
)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
}