1.首先需要在下载的接口地方加上 responseType: 'blob',
export function download(data) {
return request({
url: '',
method: '',
data,
responseType: "blob",
})
}
responseType的几种类型:
responseType值 | xhr.response 数据类型 | 说明 |
---|---|---|
" " | String字符串 | 默认值(在不设置responseType时) |
text | String字符串 | – |
document | Document对象 | 希望返回 XML 格式数据时使用 |
json | javascript对象 | 存在兼容性问题,IE10/IE11不支持 |
blob | Blob对象 | |
arrayBuffer | ArrayBuffer对象 |
2.写一个下载方法:
download(res, Name) {
if (!res.data) {
return
}
const blob = new Blob([res.data], {
type: "application/vnd.ms-excel"
})
const fileName = Name ? Name : ''
if ('download' in document.createElement('a')) { // 非IE下载
const e= document.createElement('a')
e.download = fileName + '.xlsx'
e.style.display = 'none'
e.href = URL.createObjectURL(blob)
document.body.appendChild(e)
e.click()
URL.revokeObjectURL(e.href) // 释放URL 对象
document.body.removeChild(e)
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
}
},
不同格式的文件对应的type :
文件类型 | type |
---|---|
.doc | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xls | application/vnd.ms-excel |
.txt | text/plain |
.ppt | application/vnd.ms-powerpoint |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
3.调用接口
downloadList(){
download(data).then(res=>{
this.download(res,'例如');//后端数据及文件名称
});
}