The front end exports files through the returned blob data type (with exception resolution)
Most of the web-side project development, background management or integration systems are mostly centered on data display and statistics. This kind of project is inseparable from the upload and download of files. I published an uploaded article before. This time we will talk about It is not difficult to download. Usually, the backend returns a path and downloads it directly. Today we will talk about another way to export through the blob data type. Without further ado, directly upload the code: 1. The first step is to encapsulate the
interface At this time, pass the responseType field to indicate the returned data type
//这里是封装接口的时候
exportMonitorData(params){
return httpRequest({
url: url.exportMonitorData,
method: 'post',
responseType: 'blob',//首先我们封装接口的时候要定义好返回的数据类型,传给后端
data:params,
})
},
2. It is a method that is ready to convert the blob data type into a file and download it, and call it as a public method, because it will be used in many places in the project
//这个方法封装到你的utils文件里,作为公共方法调用,这是直接导出文件的方法
export function exportData(res, name) {
const content = res
const blob = new Blob([content], {
type: 'application/ms-excel'})
const fileName = name
if ('download' in document.createElement('a')) {
// 非IE下载
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, fileName)
}
}
3. This step is the most critical, mainly dealing with abnormal situations, which will be a bit special.
decisionHttp.exportElectricity(params).then(res => {
if(res.type === 'application/json'){
//接口返回的数据类型如果是json,说明是报错信息
let reader = new FileReader();
reader.readAsText(res, 'utf-8');//这时候你的msg字段是blob类型的,不能直接用,所以数据类型要先转回来
reader.onload = ()=>{
//这里是处理异步,其他方式用不了,这里很关键
let {
msg} = JSON.parse(reader.result);//转回来是json类型,再转一次
this.$message.error(msg); //弹出错误提示
}
}else{
exportData(res, "用电分析列表.xls");//这里是上面封装的方法,传入res和文件的名字 两个参数就好了
}
});