前端文件导出
当前端需要导出excel文件时,这里以后端返回的文件流为主,此时我们可以模拟一个下载链接,直接上代码
/**
* 导出数据
*/
const handleDown = async () => {
setIsOpen(false);
setIsExporting(true);
const r = formRef.current?.getFieldsValue();
const other: any = {};
if (r.userId) {
other['userId'] = r.userId;
}
if (r.fieldName) {
other['fieldName'] = r.fieldName;
}
fetch('/api/download/excel', {
method: 'POST',
body: JSON.stringify({ templateId: Number(templateId), ...other }),
headers: {
Authorization: token || '',
'Content-Type': 'application/json, text/plain, */*',
},
responseType: 'blob',
} as any)
.then(response => {
return response.blob();
})
.then(blob => {
const url = window.URL.createObjectURL(blob);
// 创建一个下载链接并模拟点击下载
const link = document.createElement('a');
link.href = url;
link.download = `${templateName}.xlsx`; // 设置下载时的文件名
document.body.appendChild(link);
link.click();
// 清理URL对象
window.URL.revokeObjectURL(url);
})
.catch(error => {
console.error('导出失败:', error);
})
.finally(() => {
setIsExporting(false);
});
};