el-upload选择多个文件同时上传带参,on-change校验文件列表数据删除文件

样式:


form表单代码

<el-form>
<el-form-item>
  <el-row>
    <el-col :span="24">
      <el-form-item label="采集任务" prop="taskId">
        <el-select v-model="form.taskId" filterable placeholder="请选择">
          <el-option
            v-for="item in taskOptions"
            :key="item.id"
            :label="item.taskName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-col>
  </el-row>
</el-form-item>
<el-form-item>
  <el-upload
    ref="upload"
    action="/as"
    multiple
    :http-request="handleUpload"
    :on-change="handleChangeFile"
    :auto-upload="false"
    :limit="5">
    <el-button size="small" type="primary">选择文件</el-button>
    <div slot="tip" class="el-upload__tip">一次只能上传5个文件</div>
  </el-upload>
</el-form-item>
<el-form-item>
  <el-row>
    <el-col :span="24" align="center">
      <el-button type="primary" @click="handlePush"  style="margin-top: 20px">点击上传    
  </el-button>
    </el-col>
  </el-row>
</el-form-item>
</el-form>

 


data添加参数:

//任务列表
taskOptions : [],
form: {
  taskId: undefined,
},
//上传文件数组
files:[],

method方法: 

handleUpload(raw){
  this.files.push(raw.file);
},
async handlePush(){
    this.$refs.upload.submit() // 这里是执行文件上传的函数,其实也就是获取我们要上传的文件
    let fd = new FormData();
    fd.append('taskId',this.taskId)
    this.files.forEach(function (file) {
      fd.append('filename', file, file.name); // 因为要上传多个文件,所以需要遍历一下才行
    })
    
    //请求后台方法
    addCollectionDataList(fd).then(res=>{
      //请求后台成功返回处理
    })
  },
// 选择上传文件校验,
handleChangeFile(file, fileList, name) {
  let index = fileList.findIndex( fileItem => {
    return fileItem.uid === file.uid
  });
//上传文件后缀
  let extension = file.name.split(".")[1];
  if(true){  //判断条件根据自己业务    
    fileList.splice(index, 1); // 从上传文件列表删除当前选中文件
    return false;  
  }
},

java后台代码

@PostMapping("/fileUpload")
public Result fileUpload(@RequestParam("filename") MultipartFile[] files, @RequestParam("taskId")Integer taskId, HttpServletRequest request){
  //文件储存目录
  String realPath = "" ; 
  File path = new File(realPath); 
  if(!path.exists()){
   path.mkdirs(); 
  } 
  //判断file数组不能为空并且长度大于0 
  if(files != null && files.length > 0){ 
    //循环获取file数组中得文件 
    for(int i = 0;i < files.length;i++){ 
    MultipartFile file = files[i]; 
    //保存文件
    if (!file.isEmpty()){
       ..........  //执行文件保存
    }
  }
}
### 使用 `el-upload` 组件实现依次上传多个文件 为了确保文件能够按照顺序逐一上传,在使用 Element UI 的 `el-upload` 组件时,可以利用组件提供的钩子函数来控制上传行为。具体来说,通过设置属性`:auto-upload="false"` 来禁用自动上传功能[^3]。 当用户选择好所有待上传文件后,可以通过编程方式触发每个文件上传操作,并等待前一个文件完成后再继续下一个文件上传过程。下面是一个完整的解决方案: #### HTML 部分 ```html <template> <div> <!-- 文件上传区域 --> <el-upload ref="upload" action="" :auto-upload="false" :file-list="fileList" :before-upload="handleBeforeUpload" :on-change="handleChange" :on-success="handleSuccess" :on-error="handleError"> <i class="el-icon-upload"></i> <div class="el-upload__text">将文件拖到此处</div> </el-upload> <!-- 提交按钮 --> <el-button type="primary" @click="submitFiles()">提交</el-button> </div> </template> ``` #### JavaScript 方法定义部分 ```javascript <script setup> import { ref } from 'vue'; // 定义变量存储文件列表和其他状态 const fileList = ref([]); let isUploading = false; let currentIndex = -1; function handleBeforeUpload(file) { // 可在此处做文件校验逻辑 } function handleChange(file, fileListParam) { fileList.value = fileListParam; // 更新文件列表 } async function submitFiles() { if (!isUploading && fileList.value.length > 0) { isUploading = true; currentIndex = 0; await uploadNextFile(); } } async function uploadNextFile() { const fileItem = fileList.value[currentIndex]; try { await new Promise((resolve, reject) => { setTimeout(() => resolve(), 1000); // 模拟网络延迟 }); console.log(`文件 ${currentIndex + 1} 成功`); currentIndex++; if (currentIndex < fileList.value.length) { await uploadNextFile(); // 如果还有未处理的文件,则递归调用本函数 } else { finishAllUploads(); } } catch(error) { handleError(null, error); } } function handleSuccess(response, file, fileListParam) { console.log('单个文件上传成功'); } function handleError(err, response) { console.error('发生错误', err || response); stopAndNotifyFailure(); } function finishAllUploads() { isUploading = false; console.log('全部文件上传完毕'); } </script> ``` 此方案中,`submitFiles()` 函数负责启动整个上传流程;而 `uploadNextFile()` 则用于逐个发送请求并管理当前正在处理的位置索引。每当一个文件被成功输之后,便会立即尝试发起下一次上传直到所有的文件都被处理过为止。如果遇到任何失败情况会停止后续的操作并向用户提供反馈信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值