// 响应拦截器
service.interceptors.response.use(res => {
// 解析下载文件文件名
if (res.headers[“content-disposition”]) {
const disposition = decodeURIComponent(res.headers[“content-disposition”].split(‘=’)[1])
downloadFileName = disposition.substring(0, disposition.lastIndexOf(“;”)); // 中文需要转码 (前端乱码为百分号形式)
}
}
)
/**
- 通用下载方法
- @param url 接口地址:如:‘/proj/downloadFile’
- @param params {fileId: Number} 文件id
- @param filename 下载文件的名字
*/
export function download(url, params) {
return service({
url,
method: ‘get’,
responseType: ‘blob’,
params
}).then(res => {
if (res.type === ‘application/json’) {
const reader = new FileReader();
reader.readAsText(res);
reader.onload = function (e) {
const { msg } = JSON.parse(reader.result)
Message.error(msg)
}
} else {
const blob = new Blob([res])
const objectUrl = URL.createObjectURL(blob); //生成一个url
const a = document.createElement(‘a’)
a.href = objectUrl
a.download = downloadFileName
a.click()
// downloadLoadingInstance.close();
}
}).catch(® => {
// downloadLoadingInstance.close();
})
}