【发布时间】:2021-04-12 11:22:35
【问题描述】:
我有一个下载 .xls 文件的 Axios 请求。问题是作为来自后端的响应返回的对象并不总是必须是真实文件。如果我返回 json 对象而不是文件数据。那我怎么读这个json呢?
函数如下:
downloadReport() {
let postConfig = {
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
responseType: 'blob',
} as AxiosRequestConfig
axios
.post(this.urls.exportDiscountReport, this.discount.id, postConfig)
.then((response) => {
let blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
let url = window['URL'].createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = this.discount.id + ' discount draft.xlsx';
a.click();
window['URL'].revokeObjectURL(url);
})
.catch(error => {
})
}
我想阅读响应,如果它包含一些数据 - 不要创建 blob 并启动下载,而是只显示一些消息或其他内容。如果我删除 responseType: 'blob' 然后 .xls 文件下载为不可读且无效的文件。
所以问题是每个返回的响应都变成了 blob 类型,我没有在其中看到我返回的数据。有什么想法吗?
【问题讨论】: