vue2 添加页面el-upload,手动上传文件,可多次多选,上传之前容量、重名、格式校验

1、支持多次上传多选

2、容量、重名、格式校验,三种校验不成功,不执行上传动作

3、手动操作执行上传

<template>

  <div class="main">

    <div class="operate">

      <el-button @click="showAdd">新增</el-button>

    </div>

    <el-dialog title="新增" :visible.sync="addFlag">

      <div class="pop-dialog">

        <div>

          <div class="input-tit">

            <span style="color: red">*</span>

            文件名称

          </div>

          <el-input

            v-model.lazy="addForm.text"

            class="input-box"

            maxlength="42"

            placeholder="请输入"

          ></el-input>

        </div>

        <div style="margin-bottom: 12px">

          <span style="color: red">*</span>

          上传文件

        </div>

        <div class="tip-txt">注:单个文件大小不超过500MB</div>

        <el-upload

          ref="upload"

          class="upload-file-add"

          drag

          :action="uploadUrl"

          :headers="headers"

          :auto-upload="false"

          :on-success="uploadSuccess"

          mutiple

          accept=".rar,.zip,.doc,.docx,.jpg,.jpoeg,.png,.ppt,.pptx,.xls,.xlsx,.ofd,.rtf,.bmp,.mp4,.avi"

          :on-remove="uploadRemove"

          :on-change="uploadAddBefore"

        >

          <div class="upload-c">

            <i ref="up" class="el-icon-upload-file"></i>

            <div class="click-title">点击或者将文件拖拽到这里上传</div>

            <div class="format">

              支持扩展名:.rar .zip .doc .docx .pdf .jpg .jpeg .png .ppt .pptx

              .xls .xlsx .ofd .rtf .bmp .mp4 .avi

            </div>

          </div>

        </el-upload>

        <el-button type="primary" @click="uploadFnAdd">确定</el-button>

      </div>

    </el-dialog>

  </div>

</template>

<script>

import { addFile } from "@/api";

export default {

  name: "addFile",

  data() {

    return {

      addForm: {

        text: "",

      },

      addFlag: false,

      editFlag: false,

      uploadUrl: process.env.VUE_APP_BASE_API + "/FilePath/batchUpload", //返回的是带有唯一id

      headers: {

        devCode: "zhangsan",

      },

      fileReg:

        /.(xls|xlsx|rar|zip|doc|docx|pdf|jpg|jpeg|png|ppt|pptx|xls|xlsx|ofd|rtf|bmp|mp4|avi)$/i,

      fileListAdd: [],

      lastSuccessNum: 0, //上次成功添加的个数

      capacityErrorList: [], //文件容量过界的列表

      formatErrorList: [], //文件格式错误的列表

      sameNameList: [], //文件重名的列表

      timer: null,

      delay: 500,

    };

  },

  methods: {

    showAdd() {

      this.addFlag = true;

    },

    async sendSuccess() {

      if (this.fileListAdd.length == 0) {

        return this.$message({

          type: "warning",

          message: "请上传文件",

        });

      }

      let params = {

        fileList: this.fileListAdd,

        objId: "",

        trainAttachmentName: this.addForm.text,

      };

      try {

        let res = await addFile(params);

        if (res.code == 200) {

          this.$message({

            type: "success",

            message: "添加成功",

          });

          this.addFlag = false;

        }

      } catch (err) {

        console.log(err.message);

      }

    },

    uploadSuccess(value, file, fileList) {

      if (!value.success) {

        file.status = "error";

        file.name = `(上传失败)${file.name}`;

      }

      let _this = this;

      if (fileList.every((it) => it.status == "success")) {

        fileList.map((item) => {

          if (item.response) {

            if (item.response.code == 200) {

              _this.fileListAdd.push(item.response.data[0]);

            }

          }

        });

        this.sendSuccess();

      } else {

        fileList.map((item) => {

          if (item.response) {

            if (item.response.code == 200) {

              _this.fileListAdd.push(item.response.data[0]);

            }

          }

        });

      }

    },

    uploadRemove(file, fileList) {

      let objId = file.objId;

      if (file.response) {

        if (file.response.success) {

          objId = file.response.data[0].objId;

        }

      }

      this.fileListAdd = this.fileListAdd.filter((item) => item.objId != objId);

      this.lastSuccessNum = this.fileListAdd.length;

    },

    async uploadAddBefore(file, fileList) {

      //获取初始添加文件个数

      let uploadNUm = 0;

      let uploadFile = document.getElementsByClassName("upload-file-add");

      if (uploadFile && uploadFile.length > 0) {

        var upload = uploadFile[0].getElementsByTagName("input");

        if (upload && upload.length && upload[0].files.length > 0) {

          uploadNUm = upload[0].files.length;

        }

      }

      if (fileList.length - this.lastSuccessNum == 1) {

        this.capacityErrorList = [];

        this.formatErrorList = [];

        this.sameNameList = [];

      }

      if (file.status !== "ready") {

        return;

      }

      if (file.size > 1024 * 1024 * 500) {

        this.capacityErrorList.push(file.name);

      }

      let reg = this.fileReg;

      if (!reg.test(file.name)) {

        this.formatErrorList.push(file.name);

      }

      let findIndex = this.$refs.upload.uploadFiles.findIndex(

        (item) => item.name == file.name

      );

      if (findIndex > -1 && findindex < this.$refs.uploadFiles.length - 1) {

        this.sameNameList.push(file.name);

      }

      if (uploadNUm == fileList.length - this.lastSuccessNum) {

        //格式校验

        let formatStr = this.formatErrorList.join(",");

        if (formatStr) {

          this.$refs.upload.uploadFile.splice(this.lastSuccessNum, uploadNUm);

          const h = this.$createElement;

          this.$message({

            type: "error",

            duration: 2000,

            message: h("p", [

              h("span", null, "文件格式错误:"),

              h("i", { style: "color:red" }, `${formatStr}`),

            ]),

          });

          return false;

        }

        //容量校验

        let capacityStr = this.capacityErrorList.join(",");

        if (capacityStr) {

          this.$refs.upload.uploadFile.splice(this.lastSuccessNum, uploadNUm);

          const h = this.$createElement;

          this.$message({

            type: "error",

            duration: 2000,

            message: h("p", [

              h("span", null, "文件大小已超过500MB:"),

              h("i", { style: "color:red" }, `${capacityStr}`),

            ]),

          });

          return false;

        }

        //重命名校验

        let sameStr = this.sameNameList.join(",");

        if (sameStr) {

          this.$refs.upload.uploadFile.splice(this.lastSuccessNum, uploadNUm);

          const h = this.$createElement;

          this.$message({

            type: "error",

            duration: 2000,

            message: h("p", [

              h("span", null, "存在同名文件:"),

              h("i", { style: "color:red" }, `${sameStr}`),

            ]),

          });

          return false;

        }

        this.lastSuccessNum = fileList.length;

      }

    },

    uploadFnAdd() {

      this.timer && clearTimeout(this.timer);

      this.timer = setTimeout(() => {

        let uploadFiles = this.$refs.upload.uploadFiles;

        let isAllSuccess = true;

        for (let i = 0; i < uploadFiles.length; i++) {

          let item = uploadFiles[i];

          if (item.status == "error") {

            isAllSuccess = false;

            break;

          }

        }

        if (!isAllSuccess) {

          return this.$message({

            type: "warning",

            message: "请上传正确文件",

          });

        }

        if (this.addForm.text.length == 0) {

          return this.$message({

            type: "warning",

            message: "请填写正确文件名称",

          });

        }

        if (this.$refs.upload.uploadFiles.length == 0) {

          return this.$message({

            type: "warning",

            message: "请上传文件",

          });

        }

        let isFormat = true;

        let reg = this.fileReg;

        for (let j = 0; j < this.$refs.upload.uploadFiles.length; j++) {

          if (!reg.test(this.$refs.upload.uploadFiles[j].name)) {

            isFormat = false;

            break;

          }

        }

        if (!isFormat) {

          return this.$message({

            type: "error",

            message: "导入文件格式错误",

          });

        }

        if (this.isHasUnuploadAdd()) {

          let reg = /[^a-zA-Z0-9\u4E00-\u9FA5]/g;

          if (reg.test(this.addForm.text)) {

            this.$message({

              type: "error",

              message: "文件名称不允许输入特殊字符或者空格",

            });

          } else {

            this.$refs.upload.submit();

          }

        } else {

          this.sendSuccess();

        }

      }, this.delay);

    },

    isHasUnuploadAdd() {

      let isHasUnupload = false; //是否有未上传的文件

      for (let k = 0; k < this.$refs.upload.uploadFiles.length; k++) {

        let item = this.$refs.upload.uploadFiles[k];

        if (!item.response && item.status == "ready") {

          isHasUnupload = true;

          break;

        }

      }

      return isHasUnupload;

    },

  },

};

</script>

  • 21
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值