axios 請求下載檔案
阿新 • • 發佈:2021-02-06
import axios from 'axios'; axios.post(url, { ...getDataDefault(), reqBody: { ...params }, }, { responseType: 'blob' }) .then(function (response) { const { data } = response let type = data.type const relType = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'] if (type.includes('application/json')) { let reader = new FileReader() reader.onload = function (event) { let content = reader.result let message = JSON.parse(content).message // 錯誤資訊 // TODO 錯誤處理 } reader.readAsText(data) return true } else if (relType.includes(type)) { var blob = new Blob([data]) var downloadElement = document.createElement('a'); var href = window.URL.createObjectURL(blob); //建立下載的連結 downloadElement.href = href; downloadElement.download = `${name}.xlsx`; //下載後文件名 document.body.appendChild(downloadElement); downloadElement.click(); //點選下載 document.body.removeChild(downloadElement); //下載完成移除元素 window.URL.revokeObjectURL(href); //釋放掉blob物件 } }) .catch(function (error) { console.log(error); });