實現導出功能分兩種,一種是客戶端拿到數據做導出,第二種是服務器端處理好,返回一個數據流實現導出
第一種網上很容易找到,也很好用,本文要說的是第二種。
fetchExport({ id: this.sourceId, begin: this.$route.query.begin, end: this.$route.query.end }).then(res => { const blob = new Blob([res.data], { type: 'application/vnd.ms-excel', crossOrigin: 'Anonymous' }) const objectUrl = URL.createObjectURL(blob) window.location.href = objectUrl }).catch(err => { console.log(err) })
服務器端返回的是流數據,js提供了對應的處理方法,fetchExport是封裝的ajax請求方法,利用axios創建一個實例,請求頭要特別注意設置響應類型,否則下載的表格異常,如下
export function fetchExport(query) { return request({ url: '你的url', method: 'get', params: query, responseType: 'arraybuffer', // 這個一定要有 xsrfHeaderName: 'Authorization' }) }