对于后端导出接口有可能返回文件流 / JSON数据的处理

724 阅读1分钟

通过判断 axios 返回的响应类型进行判断

let res = await Axios({
    url: '',
    method: 'get',
    responseType: 'blob',  // 设置响应类型为 blob
})
if (res.type === 'application/octet-stream') {
    // 下载
}else {
    // 直接提示导出失败
}

通过FileReader + try/catch

let res = await Axios({
    url: '',
    method: 'get',
    responseType: 'blob',  // 设置响应类型为 blob
})
let blob = res // 存储文件流
let fileReader = new FileReader()
fileReader.readAsText(res, 'utf-8') // 将文件内容读取为文本字符串
fileReader.onload = (e) => {
try {
        // 当是文件流的时候 JSON.parse(e.target.result) 会抛出错误 is not valid JSON
        let res = JSON.parse(e.target.result)
        if (res.code) {
            // 不是文件流,提示错误信息
            console.log(res);
            // this.$message.error(res.message)
            this.$message.error('导出失败')
        } else {
            this.downloadBlob(blob)
        }
    } catch (error) { // 捕获错误,走下载流程
        console.log(error);
        this.downloadBlob(blob) // 调用下载接口
    }
}

通过判断响应头Content-type

let res = await Axios({
    url: '',
    method: 'get',
    responseType: 'blob',  // 设置响应类型为 blob
})
if (response.headers['content-type'] === 'application/octet-stream') { 
// 走下载
} else { 
// 提示用户
}

下载导出文件

const blob = new Blob([data], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
// 创建 a 标签进行下载
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', this.formExport.name + ".pdf");
document.body.appendChild(link);
link.click();
// 释放 URL 对象占用的内存
window.URL.revokeObjectURL(url);