umi-request获取content-disposition
2022-04-07 本文已影响0人
每日需要维生素
后端将文件流的名称放在了content-disposition,需要自己取出文件名称,代码如下
request(url, {
method: 'POST',
body: JSON.stringify(params),
responseType: 'blob',
getResponse: true // 重点
});
//导出
onExport = () => {
const { dispatch } = this.props;
let filename = ``;
dispatch({
type: 'xxx/onExport',
})
.then((res) => {
const disposition = res.response.headers.get('content-disposition');
filename = disposition
? decodeURI(disposition.split(';')[1].split("filename*=utf-8''")[1])
:null;
return res.data;
})
.then((res) => {
Modal.destroyAll();
let reader = new FileReader();
reader.readAsText(res);
reader.onload = function (result) {
try {
let resData = JSON.parse(result.target.result);
if (resData && resData.status !== 100) {
Modal.error({
title: '出错啦~',
content: resData.message || '下载失败',
});
}
} catch (err) {
if (!res.size) {
message.error('下载失败');
return false;
}
// 解析成对象失败,说明是正常的文件流
const blobUrl = window.URL.createObjectURL(res);
let clickElm = document.createElement('a');
clickElm.href = blobUrl;
clickElm.download = filename || `报表xxx.xlsx`;
clickElm.click();
window.URL.revokeObjectURL(blobUrl);
message.success('导出成功');
}
};
});
};