很多时候导出(或者下载)文件的时候,用的是超链接的方式,相当于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/
文章评论