问题描述:
后端导出excel表格为二进制 前端调取接口并下载
方案: 前端将返回数据 设置响应数据类型为blob
封装函数: /** * 后端导出excel方法 * @param postDate 接口传参 * @param interfaceUrl 接口地址 * @param excelName excel文件名 */ import {message} from 'ant-design-vue' export function exportExcel(postDate, interfaceUrl, excelName,type='post') { return new Promise((resolve, reject) => { let BASE_URL = process.env.VUE_APP_API_BASE_URL; const data = JSON.stringify(postDate); const url = BASE_URL + interfaceUrl; var xhr = new XMLHttpRequest(); xhr.open(type, url, true); xhr.responseType = "blob"; // 设置响应数据类型为blob, 不设置会出现下载的文件比源文件更大 xhr.setRequestHeader("Authorization", window.localStorage.getItem("token")); xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xhr.setRequestHeader("Accept", "application/json, text/plain, */*"); xhr.send(data); xhr.onload = function () { //判断返回的是json 还是二进制流 if (this.response.type == "application/json") { let reader = new FileReader(); reader.readAsText(this.response, "utf-8"); reader.onload = (e) => { let readerres = reader.result; let parseObj = {}; parseObj = JSON.parse(readerres); message.error(parseObj.errorMsg); resolve() }; } else { var blob = new Blob([this.response], { type: this.responseType }); // ArrayBuffer , mime类型 var a = document.createElement("a"); var url = window.URL.createObjectURL(blob); a.href = url; a.download = `${excelName}.xls`; a.click(); resolve() } }; }) }
调用:
exportExcel(请求参数, 请求地址, 下载文件名).then(res => { console.log(res); })
标签:表格,URL,excel,导出,xhr,blob,new,type From: https://www.cnblogs.com/qinyuanchun/p/17683296.html