问题
使用bold类型从后端接口获取文件流,获取成功的时候通过a标签下载;失败的时候,后端返回的是json,这个时候就无法向用户展示后端返回的错误提示信息。
思路
根据返回类型是否为 application/json 区分是否返回成功,若失败,将blob格式转换为json格式。
代码
javascript
this.$http
.post('/file/export', { exportType: 'xlsx' }, { responseType: 'blob' })
.then(res => {
if (res.data.type == 'application/json') {
const reader = new FileReader()
reader.readAsText(res.data, 'utf-8')
reader.onload = () => {
const result = JSON.parse(reader.result)
this.$message.error(result.message)
}
} else if (res.data.type == 'application/octet-stream') {
const downloadUrl = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.href = downloadUrl
document.body.appendChild(link)
link.click()
} else {
this.$message.error('导出文件类型错误!')
}
})
.catch(error => {
this.$message.error('导出文件失败!')
})