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

查看:701
本文介绍了使用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天全站免登陆