使用 POST 下载 Axios Excel 文件会导致文件损坏 [英] Axios Excel file download using POST results in corrupted file

查看:72
本文介绍了使用 POST 下载 Axios Excel 文件会导致文件损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前使用 Axios 下载由 GET 端点提供的文件.端点已更改,现在是 POST,但不需要参数.我正在更新原始下载方法,但返回的文件已损坏.

I was using Axios to download a file provided by a GET endpoint previously. The endpoint has changed and is now a POST, however the parameters are not required. I'm updating the original download method, but am getting a corrupted file returned.

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));
    }

我不确定问题是出在 responseTypeheaders,还是响应的处理方式或以上所有问题.到目前为止,我已经尝试了各种选择,但都没有运气.任何建议将不胜感激!

I'm not sure if the issue is with the responseType, headers, or how the response is handled or all of the above. I've tried various options with no luck so far. Any suggestions would be greatly appreciated!

我已经能够使用 Postman 下载文件,所以我知道端点提供的文件很好.我只是无法在我的 React 代码中整理出执行此操作的参数.

I have been able to download the file using Postman so I know the file served by the endpoint is fine. I just can't sort out the params to do this in my React code.

推荐答案

终于搞定了!问题代码块中的 post 语法不正确,还将 responseType 更改为arraybuffer".

Finally got it working! The post syntax in the code block for the question was not correct and also changed the responseType to "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));
}

这篇关于使用 POST 下载 Axios Excel 文件会导致文件损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆