接口返回文件流,前端解析
实现方式:引入axios,指定responseType值为arraybuffer,然后再回调中判断响应头content-type类型,如果是application/json,则是接口报错,这时应该抛出错误,如果是application/octet-stream,则创建a标签,模拟点击,然后销毁释放
exportExcel.js代码如下
import axios from 'axios'
import { Message } from 'element-ui'
export function exportExcel(url, data, fileName = '下载') {
axios.post(
url,
data,
{
responseType: 'arraybuffer'
}
).then(res => {
if (!res.data) return;
const blob = new Blob([res.data]);
if (res.headers['content-type'].indexOf('application/json') > -1) {
//接口报错,没有正常返回文件流
const reader = new FileReader();
reader.readAsText(blob, 'utf8');
reader.onLoad = function() {
const response = JSON.parse(reader.result);
if (response.error) {
Message({
type: 'error',
message: response.error
})
}
}
} else if (res.headers['content-type'].indexOf('application/octet-stream')) {
//正常返回文件流
const a = document.createElement('a');
a.setAttribute('download', `${fileName}.xlsx`);
a.style.display = 'none';
a.href = window.URL.createObjectURL(blob);
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
} else {}
})
}