导出excel,文件打不开
要注意responseType一定要设置
return axios({
url: '/api/esb/ddi/db/export/excel',
// url: '/test/db/export/excel',
params,
method: 'GET',
//设置blob或者arraybuffer
responseType: 'blob',
// responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
})
.then(res => {
console.log(res);
// 生产一个a标签
let link = document.createElement('a')
let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
// let blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
// let blob = new Blob([res.data], { type: 'application/msexcel;charset=utf-8' })
// 将a标签隐藏
link.style.display = 'none'
// 给a标签设置url
link.href = URL.createObjectURL(blob)
link.download = res.headers['content-disposition'] //下载后文件名
let name = link.download.split('=')[1]
name=decodeURIComponent(name)
link.download =name //下载的文件名
// 将a标签添加在body中
document.body.appendChild(link)
// 触发a标签
link.click()
// 将a标签移除
document.body.removeChild(link)
}, error => {
console.log(error);
ElMessage.error({
showClose: true,
message: '无数据',
})
})
看博客还看到他们出现了返回数据是乱码的问题,是因为
mock模块会影响原生的ajax请求,使得服务器返回的blob类型变成乱码
原文链接:https://blog.csdn.net/weixin_42142057/article/details/97655591
// 初始化 Response 相关的属性和方法
Util.extend(MockXMLHttpRequest.prototype, {
responseURL: '',
status: MockXMLHttpRequest.UNSENT,
statusText: '',
// https://xhr.spec.whatwg.org/#the-getresponseheader()-method
getResponseHeader: function(name) {
// 原生 XHR
if (!this.match) {
return this.custom.xhr.getResponseHeader(name)
}
// 拦截 XHR
return this.custom.responseHeaders[name.toLowerCase()]
},
// https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
// http://www.utf8-chartable.de/
getAllResponseHeaders: function() {
// 原生 XHR
if (!this.match) {
return this.custom.xhr.getAllResponseHeaders()
}
// 拦截 XHR
var responseHeaders = this.custom.responseHeaders
var headers = ''
for (var h in responseHeaders) {
if (!responseHeaders.hasOwnProperty(h)) continue
headers += h + ': ' + responseHeaders[h] + '\r\n'
}
return headers
},
overrideMimeType: function( /*mime*/ ) {},
responseType: '', // '', 'text', 'arraybuffer', 'blob', 'document', 'json'
response: null,
responseText: '',
responseXML: null
})