使用 POST 下载 Axios Excel 文件导致文件损坏

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)

我不知道,如果问题出在responseTypeheaders或如何响应的处理或全部的上方。到目前为止,我已经尝试了各种选择,但都没有运气。任何建议将不胜感激!

我已经能够使用 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)

  • 强烈建议您在单击链接后调用“revokeObjectURL(url)”,否则 blob 对象将保留在内存中,直到文档卸载(用户关闭选项卡!)。 (4认同)