背景:
VUE项目,下载excel需求,通过window.open可以正常下载正常显示,通过axios+blob下载的文件乱码
前端代码:
1,axios部分(request.js)
const service = axios.create({
timeout: 25000 // request timeout
})
......省略其他
2,页面API部分
import request from '@/utils/request'
// 导出
export function excel(param) {
return request({
url: '/dangerous/excel?attributesPath=' + param.attributesPath + '&tjDate=' + param.tjDate,
method: 'get'
})
}
3,blob部分
import { excel } from '@/api/dangerousVehicleDailyReport'
.......省略其他
excel(param).then((res) => {
const blob = new Blob([res.data])
const fileName = '危险品车辆日报表.xlsx'
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
const elink = document.createElement('a')
document.body.appendChild(elink)
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
elink.click()
elink.remove()
URL.revokeObjectURL(elink.href)
}
}).catch((error) => {
console.log(error)
})
解决办法:
修改request配置,增加responseType: ‘blob’
import request from '@/utils/request'
// 导出
export function excel(param) {
return requestForBlob({
url: '/dangerous/excel?attributesPath=' + param.attributesPath + '&tjDate=' + param.tjDate,
method: 'get',
responseType: 'blob'
})
}