调用导出接口,处理两种情况:
一种是返回文件流实现导出,另一种返回json报错信息,需要提示错误信息。
type DaoChuType = 'zip' | 'xls'
function daoChuExcel(url: string, params: any, title: string, type: DaoChuType) {
http({
url: url,
data: params,
method: 'POST',
responseType: 'blob',
}).then((response) => {
const reader = new FileReader()
reader.readAsText(response.data, 'utf-8')
reader.onload = (e) => {
// 如果是json则提示报错信息 《此处是重点》
if (typeof reader.result === 'string' && reader.result.includes('code') && reader.result.includes('msg')) {
return handle({ data: JSON.parse(reader.result as string) })
} else {
//导出文件
const blob = new Blob([response.data], {
type: 'application/vnd.ms-excel', //将会被放入到blob中的数组内容的MIME类型
})
const objectUrl = URL.createObjectURL(blob) //生成一个url
downloadFile(objectUrl, title)
}
}
})
}
function downloadFile(content, filename) {
const a = document.createElement('a')
a.href = content
a.download = filename
a.click()
}