我以前使用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)); }
我不知道,如果问题出在responseType,headers或如何响应的处理或全部的上方。到目前为止,我已经尝试了各种选择,但没有运气。任何建议将不胜感激!
responseType
headers
我已经能够使用Postman下载文件,所以我知道端点提供的文件很好。我只是无法在我的React代码中理清参数来做到这一点。
终于成功了!该post问题的代码块中的语法不正确,并且也将其更改responseType为“ arraybuffer”。
post
下面的工作示例:
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)); }