vue+axios實現檔案下載——請求的responseType為blob
阿新 • • 發佈:2020-12-03
vue+axios實現檔案下載
功能:點選匯出按鈕,提交請求,下載excel檔案;
第一步:跟後端童鞋確認交付的介面的response header設定了
以及返回了檔案流。
第二步:修改axios請求的responseType為blob,以post請求為例:
axios({ method: 'post', url: 'api/user/', data: { firstName: 'Fred', lastName: 'Flintstone' }, responseType: 'blob' }).then(response => { this.download(response) }).catch((error) => { })
第三步:請求成功,拿到response後,呼叫download函式(建立a標籤,設定download屬性,插入到文件中並click)
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() } }