el-upload的自定义上传excel
时间: 2025-01-31 22:56:39 AIGC 浏览: 74
### 实现 `el-upload` 组件自定义上传 Excel 文件
为了实现通过 Element UI 的 `el-upload` 组件来定制化上传 Excel 文件,可以按照如下方式构建:
#### HTML 部分
创建一个用于触发文件选择对话框的按钮,并指定接受的文件类型为 `.xlsx`, `.xls`。
```html
<template>
<div class="upload-excel">
<el-upload
ref="upload"
:auto-upload="false"
:on-change="handleChange"
action=""
accept=".xlsx, .xls"
:limit="1"
:file-list="fileList"
:class="{ 'disUoloadSty': hideUploadButton }"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<p v-if="!hideUploadButton && fileList.length === 0" style="margin-top:8px;">点击或拖拽Excel文件到此处</p>
</el-upload>
<el-button @click="submitUpload" style="margin-left: 10px;" type="success" plain>上传至服务器</el-button>
</div>
</template>
```
上述模板中包含了两个主要部分:一个是用来触发文件选择器的按钮;另一个则是实际执行上传操作的按钮。这里还设置了当选择了文件之后不再显示默认的文字提示[^1]。
#### JavaScript/TypeScript 部分
接下来,在脚本里定义处理逻辑,包括改变事件处理器以及提交表单的方法。
```javascript
<script setup lang="ts">
import { ref } from 'vue';
// 假设这是你的Vue组合API环境下的代码
const upload = ref(null);
let fileList = ref([]);
let hideUploadButton = ref(false);
function handleChange(file, fileList) {
if (file.raw.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" &&
file.raw.type !== "application/vnd.ms-excel") {
this.$message.error('仅支持.xlsx 或者.xls 格式的文件');
return;
}
// 清除之前的文件列表并更新新的状态
fileList.value = [file];
hideUploadButton.value = true;
}
async function submitUpload() {
const formData = new FormData();
formData.append('excelFile', fileList.value[0].raw);
try {
await fetch('/api/upload/excel', {
method: 'POST',
body: formData,
});
console.log('文件已成功上传!');
} catch(error){
console.error('上传失败:', error.message);
}
}
</script>
```
这段脚本实现了对文件类型的验证,并且只允许一次性的单一文件上传。一旦用户选定了有效的 Excel 文件,则会将其加入到待上传队列当中,并隐藏掉原有的上传按钮[^2]。
#### CSS 部分
最后是控制样式的CSS规则,这部分已经在提供的引用中有提及过,主要用于调整上传区域大小及隐藏上传按钮后的样式效果。
```css
<style scoped>
.uoloadSty .el-upload--picture-card{
width:110px;
height:110px;
line-height:110px;
}
.disUoloadSty .el-upload--picture-card{
display:none; /* 上传按钮隐藏 */
}
</style>
```
此段样式确保了即使在不满足条件的情况下也能保持良好的用户体验界面设计。
阅读全文
相关推荐



















