Axios使用POST方式导出、下载文件

2021-08-09 872点热度 0人点赞 0条评论

很多时候导出(或者下载)文件的时候,用的是超链接的方式,相当于window.location.href='xxx.xlsx'的方式,很容易实现文件的导出下载,不过一般是针对API采用GET的方式,如果后台API是POST的方式呢?

其实也很简单,这里介绍在Vue.js下采用了axios来post请求,并下载文件,示例如下:

downloadExportExcel() {
    var payload = {"start":"2021-07-11","end":"2021-07-22"};
    axios.post('http://192.168.1.1:8081/api/export_excel', payload,
        {
            headers:
                {
                    'Content-Disposition': "attachment; filename=export.xlsx",
                    'Content-Type': 'application/octet-stream'
                },
            responseType: 'arraybuffer',//or responseType: 'blob', //important
        }
    ).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'export.xlsx');
        document.body.appendChild(link);
        link.click();
        link.remove();
    }).catch((error) => console.log(error));
}

如果是GET方式,详见:https://blog.terrynow.com/2022/09/07/axios-download-or-export-file-using-get-with-custom-header-token/

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论