這段時間在開發後臺管理系統,管理員要看自定義數據報表,因此要求可以把數據以excel表格形式導出,剛開始我是直接用get方式下載的,後來後臺同事說要改post下載,改就改吧,下面說說這兩種下載方式,提供給你們參考:javascript
1.get 下載:java
var downURL = '下載接口' var getData = '?starTime=20180922&endTime=20180925' var request = downURL+getData window.open(request)
2.post下載ios
第一步:讓後端將下載的接口的response header設置:axios
Content-disposition: attachment; filename=數據報表.xlsx(表示會直接下載文件,文件名爲‘數據報表’)後端
Content-Type:application/octet-stream (二進制流數據,如常見的文件下載)app
第二步:修改axios請求的responseType爲blob,以post請求爲例:函數
axios({ method: 'post', url: '接口地址', data: { startTime: '20180922', endTime:'20180925' }, responseType: 'blob' }).then(response => { this.download(response) }).catch((error) => { })
第三步:請求成功,拿到response後,調用download函數post
methods: { download (data) { if (!data) { return } let url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', 'excel.xlsx') document.body.appendChild(link) link.click() } }