- 下载word
downFileFn (url: any, fileName: any, data: any) { // 导出
axios.get(url, {
responseType: 'blob',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
params: data
}).then((res: any) => {
const blob = res.data //接收的数据
// 用fileReader对象进行数据转换和输出
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = (e: any) => {
// 创建a标签
const a: any = document.createElement('a')
// 给下载文件命名
a.download = fileName
a.href = e.target.result
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
}).catch((err: any) => {
console.log(err.message)
})
}
- 下载zip
downZipFileFn (url: any, fileName: any, data: any) { // zip文件下载
axios.get(url, {
responseType: 'blob',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
params: data
}).then((res: any) => {
console.log(res.data, 'zip下载')
const blob = new Blob([res.data], { type: 'application/zip' })
// 设置路径
const url = window.URL.createObjectURL(blob)
// 创建a标签
const link = document.createElement('a')
link.href = url
link.download = fileName // 重命名文件
link.click()
URL.revokeObjectURL(url)
}).catch((error: any) => {
throw error
})
}
- 下载excel
downExcelFn (url: any, fileName: any) { // elcxel下载
axios.get(url, {
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then((res: any) => {
if (res.status === 200) {
console.log(res.data, 'excel下载')
const blob = new Blob([res.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
})
const objectUrl = URL.createObjectURL(blob)
// 创建a标签
const link = document.createElement('a')
const fname = fileName
link.href = objectUrl
link.setAttribute('download', fname)
document.body.appendChild(link)
link.click()
} else {
console.log(res.data)
}
})
}
爱分享的前端人!
看不懂可私聊哟~