Element UI 实现多文件上传并等待上一个文件上传完成再触发下一个文件上传
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                在Element UI中实现多文件上传,并且要求上传完一个文件后再开始上传下一个文件,可以通过监听文件上传组件的on-success事件来实现。以下是一个简单的示例代码:
<template>
  <el-upload
    :action="uploadUrl"
    :on-success="handleSuccess"
    :before-upload="handleBeforeUpload"
    :file-list="fileList"
    list-type="text">
    <el-button size="small" type="primary">点击上传</el-button>
  </el-upload>
</template>
 
<script>
export default {
  data() {
    return {
      uploadUrl: '/upload', // 你的上传API地址
      fileList: [],
      currentUploadIndex: 0,
    };
  },
  methods: {
    handleBeforeUpload(file) {
      // 可以在这里添加更多的文件校验逻辑
      this.fileList.push(file);
      return false; // 阻止默认上传
    },
    handleSuccess(response, file, fileList) {
      // 成功上传一个文件后的回调
      this.currentUploadIndex++;
      if (this.currentUploadIndex < this.fileList.length) {
        // 如果还有文件未上传,则继续上传下一个文件
        const nextFile = this.fileList[this.currentUploadIndex];
        this.uploadFile(nextFile);
      }
    },
    uploadFile(file) {
      // 创建FormData并模拟上传
      const formData = new FormData();
      formData.append('file', file);
 
      // 使用axios或者其他HTTP库进行文件上传
      // 这里只是示例,需要替换为实际的上传逻辑
      axios.post(this.uploadUrl, formData, {
        onUploadProgress: progressEvent => {
          if (progressEvent.lengthComputable) {
            // 可以在这里更新文件上传的进度
          }
        }
      }).then(response => {
        this.handleSuccess(response.data, file, this.fileList);
      }).catch(error => {
        // 处理上传失败的逻辑
      });
    }
  }
};
</script>在这个示例中,我们使用了el-upload组件的before-upload钩子来收集所有待上传的文件,并通过一个变量currentUploadIndex来跟踪当前正在上传的文件索引。handleSuccess方法会在每次上传成功后被调用,如果还有未上传的文件,它会继续上传下一个文件。
注意:实际的文件上传逻辑需要替换为你的服务器API调用。这里使用了axios库来模拟文件上传,你需要根据实际项目中的HTTP库进行相应的调整。
评论已关闭