需求
使用Element UI 中的el-upload组件实现文件上传和下载的功能。本文将介绍如何使用 Element UI 组件库实现 Excel 文件的上传和下载功能。后台接口返回的是数据流。
image.png
技术栈
- Vue.js
- Element UI
- Fetch API
实现步骤
1. 设置 HTML 结构
首先,我们需要在 HTML 中引入 Element UI 的样式和 Vue.js 库:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Element UI File Upload</title>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<!-- 文件上传组件 -->
<el-upload>
<!-- 省略其他属性和内容 -->
</el-upload>
<!-- 下载链接和按钮 -->
<div v-if="downloadUrl">
<a :href="downloadUrl" target="_blank">下载 Excel 文件</a>
<el-button type="primary" @click="downloadExcel">下载</el-button>
</div>
</div>
</body>
</html>
2. 实现文件上传功能
在 Vue 实例中,我们需要定义一些数据和方法来实现文件上传功能:
new Vue({
el: '#app',
data() {
return {
fileList: [],
downloadUrl: ''
}
},
methods: {
uploadFile(params) {
// 构建表单数据
const formData = new FormData();
formData.append('file', params.file);
formData.append('item', '');
// 发送 POST 请求到上传接口
fetch('https://wwwbaidu.com/dc/excelHandle', {
method: 'POST',
body: formData
})
.then(response => {
// 检查返回状态
if (response.ok) {
// 获取二进制数据
return response.blob();
} else {
console.error('Upload error:', response.status);
return Promise.reject(response.status);
}
})
.then(blob => {
console.log('Upload success:', blob);
// 上传成功后更新文件列表
this.fileList.push({name: params.file.name, url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'});
// 将返回的字节码转换成 Excel 文件并提供下载地址
this.convertByteCodeToExcel(blob);
})
.catch(error => {
console.error('Upload error:', error);
});
}
}
})
在 uploadFile
方法中,我们使用 Fetch API 发送 POST 请求到上传接口,并在成功回调中更新文件列表和转换字节码为 Excel 文件。
3. 实现 Excel 文件下载功能
接下来,我们需要实现将字节码转换为 Excel 文件并提供下载链接:
methods: {
convertByteCodeToExcel(byteCode) {
// 将字节码转换成 Blob 对象
const blob = new Blob([byteCode], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// 创建下载链接
this.downloadUrl = URL.createObjectURL(blob);
},
downloadExcel() {
// 触发下载
const link = document.createElement('a');
link.href = this.downloadUrl;
link.setAttribute('download', 'excel_file.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
在 convertByteCodeToExcel
方法中,我们将返回的字节码转换成 Blob 对象,并创建一个下载链接。在 downloadExcel
方法中,我们触发下载操作。
总结
通过以上步骤,我们成功实现了 Excel 文件的上传和下载功能。在实际开发中,您可以根据需求进一步完善这个 demo,比如添加文件类型和大小的校验,以及错误处理等。
希望本文对您有所帮助。如果您有任何疑问或建议,欢迎随时与我交流。