tw1*_*742 10 excel reactjs axios
我以前使用 Axios 下载由 GET 端点提供的文件。端点已更改,现在是 POST,但不需要参数。我正在更新原始下载方法,但返回的文件已损坏。
downloadTemplate() {
axios.post(DOWNLOAD_TEMPLATE_URL,
{
responseType: 'blob',
headers: {
'Content-Disposition': "attachment; filename=template.xlsx",
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'template.xlsx');
document.body.appendChild(link);
link.click();
})
.catch((error) => console.log(error));
}
Run Code Online (Sandbox Code Playgroud)
我不知道,如果问题出在responseType,headers或如何响应的处理或全部的上方。到目前为止,我已经尝试了各种选择,但都没有运气。任何建议将不胜感激!
我已经能够使用 Postman 下载文件,所以我知道端点提供的文件很好。我只是无法在我的 React 代码中整理出执行此操作的参数。
tw1*_*742 23
终于让它工作了!该post问题的代码块中的语法不正确,并将其更改responseType为“arraybuffer”。
下面的工作示例:
downloadTemplate() {
axios.post(DOWNLOAD_TEMPLATE_URL, null,
{
headers:
{
'Content-Disposition': "attachment; filename=template.xlsx",
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
},
responseType: 'arraybuffer',
}
).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'template.xlsx');
document.body.appendChild(link);
link.click();
})
.catch((error) => console.log(error));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10570 次 |
| 最近记录: |