1. pdf下载,设置axios 的responseType为 'arraybuffer'
downloadPdf: (data: object) => {
return request({
url: `xxxx`,
method: 'post',
responseType: "arraybuffer",
data
})
}
方法调用:
const Download = function () {
const params = {
docType: 'pdf',
resultId: state.tableData.resultId
}
const loading = ElLoading.service({
lock: true,
text: '加载文件中,文件较大请耐心等待...',
background: 'rgba(0, 0, 0, 0.7)',
})
downloadPdf(params).then((res) => {
loading.close()
console.log(res)
let url = window.URL.createObjectURL(
new Blob([res], {
type: "application/pdf;charset=utf-8",
})
);
console.log(url)
if (url) {
window.open(url, "_blank");
}
}).catch((err) => {
loading.close()
console.log(err)
});
}
2. word下载,设置axios 的responseType为 'blob'
downloadWord: (data: object) => {
return request({
url: `xxxx`,
method: 'post',
responseType: "bob",
data
})
}
调用方法
const onDown = () => {
let params = {
fileName: state.name,
html: html
}
downloadWord(params).then(data => {
if (!data) {
tool.message("文件导出失败", 'error')
return
}
const content = data
const blob = new Blob([content])
const name = state.title;
const fileName = name+'.docx'
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a')//创建一个a标签通过a标签的点击事件区下载文件
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)//使用blob创建一个指向类型数组的URL
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
}
})
}
3.下载excel,设置axios 的responseType为 'blob'
downloadExcel: (data: object) => {
return request({
url: `xxxx`,
method: 'post',
responseType: "bob",
data
})
}
调用方法:
const onDown = () => {
downloadExcel().then((data) => {
if (!data) {
tool.message("文件下载失败", 'error')
return
}
const content = data
const blob = new Blob([content])
const name = 'xx模板';
const fileName = name+'.xls'
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a')//创建一个a标签通过a标签的点击事件区下载文件
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)//使用blob创建一个指向类型数组的URL
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
}
}).catch(() =>{})
}