实现两个el-upload
时间: 2025-01-10 14:14:27 浏览: 32
### 实现两个文件上传组件
为了满足需求,在Element UI中配置和使用两个`el-upload`组件,可以按照如下方式设置:
#### 自定义上传行为
通过属性`auto-upload="false"`来控制自动上传的行为关闭,这样可以在点击按钮之后再触发自定义的逻辑处理函数。对于每个`el-upload`实例来说,可以通过监听事件`on-change`来进行更细粒度的操作。
```html
<template>
<div>
<!-- 文件上传组件一 -->
<el-upload
class="upload-demo"
ref="uploadOne"
:before-upload="handleBeforeUpload"
:on-change="handleChangeFile1"
auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取第一个文件</el-button>
</el-upload>
<!-- 文件上传组件二 -->
<el-upload
class="upload-demo"
ref="uploadTwo"
:before-upload="handleBeforeUpload"
:on-change="handleChangeFile2"
auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取第二个文件</el-button>
</el-upload>
<el-button style='margin-top: 20px;' @click="submitFiles()">提交全部文件</el-button>
</div>
</template>
```
#### JavaScript部分
在JavaScript代码里,定义好相应的回调函数用于处理不同阶段的任务,比如验证文件格式、记录文件信息以及最终执行实际的上传过程等。
```javascript
<script>
export default {
data() {
return {
fileList1: [], // 存储第一个文件的信息
fileList2: [] // 存储第二个文件的信息
};
},
methods: {
handleChangeFile1(file, fileList) {
this.fileList1 = fileList.slice(-1); // 只保留最新的一个文件
},
handleChangeFile2(file, fileList) {
this.fileList2 = fileList.slice(-1);
},
handleBeforeUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 2MB!');
}
return isLt2M && !this.checkFileType(file.name)[^4];
},
checkFileType(fileName){
let extensionStr = fileName.substring(fileName.lastIndexOf('.') + 1).toUpperCase();
let acceptFileType=['JPG','PNG','MP4'];//允许的文件类型
return acceptFileType.includes(extensionStr.toUpperCase());
},
submitFiles(){
var formData=new FormData();
if(this.fileList1.length>0){
formData.append("file",this.fileList1[0].raw,"first_file");
}
if(this.fileList2.length>0){
formData.append("file",this.fileList2[0].raw,"second_file");
}
axios.post('/your/custom/upload/endpoint',formData,{
headers:{'Content-Type':'multipart/form-data'}
}).then(response=>{
console.log(response.data);
});
}
}
};
</script>
```
此方案实现了两个独立工作的`el-upload`控件,并且能够区分不同的文件输入并将其作为单个请求的一部分发送出去[^1]。
阅读全文
相关推荐


















