1、a标签下载
前端创建超链接,通过a标签的链接向后端服务发get请求,接收后端的文件流,非常简单
<a :href='"/user/downloadExcel"' >下载模板</a>
另一种情况是创建div标签,动态创建a标签:
<div name="downloadfile" onclick="downloadExcel()">下载</div>
function downloadExcel() {
let a = document.createElement('a')
a.href ="/user/downloadExcel"
a.click();
}
还有一种补充:
function downloadExcel() {
window.location.href = "/tUserHyRights/downloadUsersUrl";
}
注意: 一般这样下载文件的都是不带token等验证的下载方法,如果必须带token,可以和后端协商在href后面拼接,然后后端去接受验证
2、iframe
<el-button size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport(scope.row)">导出</el-button>
handleExport(row) {
var elemIF = document.createElement('iframe')
elemIF.src = 'user/downloadExcel?snapshotTime=' + formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm') +
'&category=' + row.category
elemIF.style.display = 'none'
document.body.appendChild(elemIF)
}
3、通过按钮触发调用接口,对后端发的post请求,使用blob格式
<el-button size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport(scope.row)">导出</el-button>
handleExport(row){
const url="/user/downloadExcel"
const options = {snapshotTime:formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm')}
exportExcel(url,options)
}
export function exportExcel(url, options = {}) {
return new Promise((resolve, reject) => {
console.log(`${url} 请求数据,参数=>`, JSON.stringify(options))
axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
axios({
method: 'post',
url: url,
data: options,
responseType: 'blob'
}).then(
response => {
resolve(response.data)
let blob = new Blob([response.data], {
type: 'application/vnd.ms-excel'
})
console.log(blob)
let fileName = Date.parse(new Date()) + '.xlsx'
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName)
} else {
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
window.URL.revokeObjectURL(link.href)
}
},
err => {
reject(err)
}
)
})
}
this.$http( {
method: 'post',
url: ' ',
data: mData,
responseType: ' blob'
}).then(res ={
const link = document.createElement('a')
const blob = new Blob([res.data])
link.style.display = 'none'
link.href = URL.cteateObjectURL(blob)
link.download = ' 文件名'
document. body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(link.href)
}).catch(err => {
this.$notify.error({
message: 'error',
duration: 1000
})
}). finally({
})
这样调用接口,不用担心token等验证问题.
注意:虽然不用担心token验证,但是一般通过接口返回的是数据,会默认在返回里面打开,只能看到完整的数据,但并不会变成下载,所以此处需要通过原生js创建一个a标签链接,设置隐藏属性以及默认点击,通过把数据转成Blob的方式,通过 URL.createObjectURL转化成href的格式被a标签识别,点击后再清除数据和a标签,谨防下次下载数据残留
|