引用:https://www.jianshu.com/p/e449196a8d39

    <el-upload
      multiple
      action=""
      :limit="5"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :auto-upload="false"
      :file-list="fileList"
      :on-exceed="handleExceed"
    >
      <el-button slot="trigger" size="small" type="primary" @click="resetFileCount">选取文件</el-button>
      <el-button size="small" type="success" @click="submitUpload">上传到服务器{{url}}</el-button>
    </el-upload>
   resetFileCount(){
          this.fileCount = 0;
        },
        handleChange(file,fileList){// 文件状态改变钩子
          // 第一次on-change获取fileList
          console.log("ccccccccccccccccccc",this.fileCount);
          console.log("**********************************");
          if (this.fileCount === 0){
            // 多个文件fileList会变化
            this.oldFileList = Object.assign(this.fileList);
          }

          console.log(this.oldFileList,2222);
          // file.raw // 文件内容
          // 改文件是否已经存在上传列表中  some判断是否满足要求
          let isTrue = this.oldFileList.some((f)=>{
            console.log(f.name,file.name);
            return f.name === file.name})


          if (isTrue){
            this.$message.warning("请勿重复上传文件!")
            fileList.pop()
            return
          }
          this.fileList = fileList

          this.fileCount++;

        },
        handleRemove(file,fileList){// 删除上传文件
          this.fileList = fileList
        },

      submitUpload(){ // 提交点击
        if (this.fileList.length === 0){
          this.$message.warning("请先选择上传文件!")
          return
        }
        this.uploadFile()
      },
        uploadFile(){//文件上传方法
          let formData = new FormData();
          this.fileList.forEach(file =>{
            //multipartFiles 后台接收名字
            formData.append("multipartFiles",file.raw)
          })
          console.log(formData);
          //后端用 multipartFiles 接收
          axios.post(this.url,formData,{"Content-Type":"multipart/form-data"})
        },
        dialogClose(){ // 关闭dialog
          this.$parent.closeAttachmentDialog()
        },
        handleExceed(){// 超出限制个数钩子
          this.$parent.handleExceed()

        },

遇到的问题:
一次性上传多个文件时,他的on-change就会执行很多次,也会上传很多次。。上面的代码是自动上传的,也有判断文件个数是否等于 fileList 的长度是否相等,相等再上传。。。
一次性上传多个文件时,判断上传文件是否重复,设置一个fileCount 文件计数器
在这里插入图片描述
在这里插入图片描述
每次选择文件的时候设置为0 ,将最初的fileList存起来
在这里插入图片描述
不然每一个文件都会执行on-change,都会初始化fileList,就不能根据fileList判断是否有这个文件


在这里插入图片描述


在这里插入图片描述
在这里插入图片描述

引用:https://blog.csdn.net/qq_42394457/article/details/96769170、https://blog.csdn.net/weixin_43915587/article/details/91953230

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐