【方法1—通过 a 标签 download 属性结合 blob 构造函数下载】
reportTotal.vue
<template>
<div class="reportTotal">
<el-button type="primary" @click="handleExport">导出</el-button>
</div>
</template>
<script>
import reportTotal from '@/api/reportTotal'
export default {
data(){
return {
dateStr: ''
}
},
methods: {
handleExport(){
let temp = {dateStr: this.dateStr}//2021-05
reportTotal.exportExcel(temp).then(res =>{
const blob = new Blob([res.data],{type: 'application/vnd.ms-excel;charset=utf-8'})//构造一个blob对象来处理数据并设置文件类型
const href = window.URL.createobjectURL(blob)//创建新的URL表示指定的blob对象
const element = document.createElement('a')//创建a标签
element.href = href//指定下载链接
element.download = '数据治理报表.xls'//下载文件名
document.body.appendchild(element)//将a标签插入页面中
element.click()//触发下载
document.body.removeChild(element)//清除a标签
window.URL.revokeObjectURL(href)//释放URL对象
})
}
}
}
</script>
reportTotal.js
import request from '@/request'
export default {
exportExcel(data){
return request({
url: '/exposure/export/exporttotalList',//服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默认是'json'
method: 'get',
response: 'blob',
params: data
})
}
}
注:请求后台接口时要在请求头上加{responseType: ‘blob’};download 设置文件名时,可以直接设置扩展名,如果没有设置浏览器将自动检测正确的文件扩展名并添加到文件。
【方法2—通过 url 下载】
即后端提供文件的地址,直接使用浏览器去下载
通过 window.location.href = 文件路径下载
window.location.href = ${location.origin}/exposure/export/exporttotalList
通过 window.open(url, ‘_blank’)
window.open(${location.origin}/exposure/export/exporttotalList
)
这两种使用方法的不同:
window.location:当前页跳转,也就是重新定位当前页;只能在网站中打开本网站的网页。
window.open:在新窗口中打开链接;可以在网站上打开另外一个网站的地址。
【方法3—通过 js-file-download 插件下载】
安装:npm install js-file-download --S
使用:
import fileDownload from 'js-file-download'
axios.get(`/exposure/export/exporttotalList`, {
responseType: 'blob' //返回的数据类型
})
.then(res => {
fileDownload(res.data, this.fileName)
})