vue elementui实现下载
使用 ElementUI 实现文件下载
在 Vue 项目中结合 ElementUI 实现文件下载功能,可以通过以下方法实现。假设后端已提供文件下载接口,前端通过请求接口获取文件并触发下载。
通过 axios 下载文件
安装 axios 并引入到项目中:
npm install axios
在 Vue 组件中调用下载接口:

import axios from 'axios';
export default {
methods: {
downloadFile() {
axios({
url: '/api/download', // 替换为实际接口地址
method: 'GET',
responseType: 'blob', // 重要:指定响应类型为 blob
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'filename.ext'); // 设置下载文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
}
}
结合 ElementUI 按钮触发下载
在模板中使用 ElementUI 的按钮组件触发下载:
<template>
<el-button type="primary" @click="downloadFile">下载文件</el-button>
</template>
处理后端返回的文件名
如果后端在响应头中返回文件名,可以通过以下方式获取:

axios({
url: '/api/download',
method: 'GET',
responseType: 'blob',
}).then(response => {
const contentDisposition = response.headers['content-disposition'];
let fileName = 'default.ext';
if (contentDisposition) {
const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/);
if (fileNameMatch && fileNameMatch[1]) {
fileName = fileNameMatch[1];
}
}
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
显示下载进度
使用 ElementUI 的进度条组件显示下载进度:
<template>
<div>
<el-button type="primary" @click="downloadFile">下载文件</el-button>
<el-progress :percentage="downloadProgress" v-if="downloadProgress > 0"></el-progress>
</div>
</template>
<script>
export default {
data() {
return {
downloadProgress: 0
};
},
methods: {
downloadFile() {
this.downloadProgress = 0;
axios({
url: '/api/download',
method: 'GET',
responseType: 'blob',
onDownloadProgress: progressEvent => {
this.downloadProgress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
}
}).then(response => {
this.downloadProgress = 100;
// 处理文件下载
});
}
}
};
</script>
错误处理
添加错误处理逻辑,使用 ElementUI 的 Message 组件提示用户:
downloadFile() {
axios({
url: '/api/download',
method: 'GET',
responseType: 'blob',
}).then(response => {
// 处理文件下载
}).catch(error => {
this.$message.error('下载失败: ' + error.message);
});
}
以上方法结合了 Vue、ElementUI 和 axios 实现了文件下载功能,包括进度显示和错误处理。根据实际需求调整接口地址和文件名处理逻辑即可。






