1.创建超链接,通过a标签的链接向后端服务发get请求,接收后端的文件流
<a :href='"/user/downloadExcel"' >下载模板</a>
2.创建iframe的方式
<el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-button>
handleDownload(row) {
this.loadingOverLay = this.$loading({
lock: true,
text: "文件生成中",
spinner: "el-icon-loading",
background: "rgba(0,0,0,0.7)",
});
var elemIF = document.createElement("iframe");
elemIF.src = process.env.VUE_APP_BASE_API + "/transcode/download/" + row.id;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
this.loadingOverLay.close();
},
3.对后端发的post请求,使用blob格式
<el-button size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport(scope.row)">导出</el-button>
//method方法
handleExport(row){
const url="/user/downloadExcel"
const options = {snapshotTime:formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm')}
exportExcel(url,options)
}
//api.js
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) {
// console.log(2)
navigator.msSaveBlob(blob, fileName)
} else {
// console.log(3)
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
//释放内存
window.URL.revokeObjectURL(link.href)
}
},
err => {
reject(err)
}
)
})
}
4.导出json文件
1.安装:
npm install file-saver --save
2.引入:
import FileSaver from 'file-saver'
const blob = new Blob([JSON.stringify(data, null, 2)], {type: 'application/json'})
FileSaver.saveAs(blob, '文件名.json')
到此这篇关于VUE+ElementUI下载文件的几种方式(小结)的文章就介绍到这了,更多相关VUE ElementUI下载文件内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!