表格中上传文件的表单验证

表格中上传文件的表单验证_第1张图片

<template>
  <!-- 新增记录 -->
  <div class="newRecord">
    <div class="danger-detail">
      <div class="detail-right">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="附件:" prop="fileList">
            <fileUpload1 :fileType="['jpg','jpeg','png', 'MP4']" :fileSize="20" :value="fileList" :isView="false" :limit="10" @input="uploadSuccess" />
          </el-form-item>
          <div class="eventClass">
            <el-form-item label="附件及说明:" prop="tableData">
            </el-form-item>
            <div>
              <el-table :data="ruleForm.tableData" border style="width: 100%;" class="table-class">
                <el-table-column label="附件名称" align="center">
                  <template v-slot="scope">
                    <el-form-item :prop="'tableData.'+scope.$index+'.fileListTable'" :rules="rules.fileListTable">
                      <el-upload :style="{display:scope.row.isDiaplay}" :action="uploadFileUrl" :before-upload="beforeUpload" :show-file-list="false" :headers="headers" :data="{ bucketName }" :on-success="handleUploadSuccess" :limit="1" :file-list="scope.row.fileListTable">
                        <el-button icon="el-icon-plus" @click="handleUpload(scope)">上传文件</el-button>
                      </el-upload>
                      <li class="el-upload-list__item ele-upload-list__item-content" v-for="(file, indexText) in scope.row.fileListTable" :key="indexText+1">
                        <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
                          <span class="el-icon-document"> {{ file.name }} </span>
                        </el-link>
                        <div class="ele-upload-list__item-content-action">
                          <el-link :underline="false" @click="handleDelete1(scope.$index)" type="danger">删除</el-link>
                        </div>
                      </li>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="附件说明" align="center">
                  <template v-slot="scope">
                    <el-form-item :prop="'tableData.'+scope.$index+'.instructions'" :rules="rules.instructions">
                      <el-input v-model="scope.row.instructions"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button icon="el-icon-plus" style="width: 100%;margin-top: 10px;" @click="handleAdd">新增附件及说明(附件支持png、jpg、jpeg、mp4格式)</el-button>
            </div>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleDialogVisible('ruleForm')">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "newRecord",
  props: {
    form: {
      type: Object,
      default: null,
    },
  },
  data() {
    var uploadText = (rule, value, callback) => {
      console.log("sdfsdfs:", value);
      if (value.length == 0) {
        callback(new Error("请上传文件"));
      } else {
        callback();
      }
    };
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/base/minio/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      bucketName: "gas",
      ruleForm: {
        fileList: [],
        tableData: [
          {
            instructions: "",
            isDiaplay: "block",
            fileListTable: [
              // {
              //   name: "food.jpeg",
              //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
              // },
            ],
          },
        ],
      },
      fileList: [],
      rules: {
        fileList: [
          { required: true, message: "请上传附件", trigger: "change" },
        ],
        tableData: [{ required: true, message: "", trigger: "change" }],
        fileListTable: [{ validator: uploadText, trigger: "change" }],
        instructions: [
          { required: true, message: "请添加附件说明", trigger: "change" },
        ],
      },
      indexVal: "", //当前点击的是第几行表格
    };
  },
  created() {},
  watch: {
    "ruleForm.fileList": {
      handler(newVal) {
        if (newVal.length > 0) {
          // 判断是否显示了请上传文件,如果显示了,则进行隐藏
          let divCon = document.getElementsByClassName("el-form-item__error");
          if (divCon.length > 0) {
            for (var i = 0; i < divCon.length; i++) {
              if (divCon[i].innerText.replace(/\s*/g, "") == "请上传附件") {
                divCon[i].style.display = "none";
              }
            }
          }
        } else {
          let divCon = document.getElementsByClassName("el-form-item__error");
          if (divCon.length > 0) {
            for (var i = 0; i < divCon.length; i++) {
              if (divCon[i].innerText.replace(/\s*/g, "") == "请上传附件") {
                divCon[i].style.display = "block";
              }
            }
          }
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.$nextTick(() => {});
  },
  methods: {
    uploadSuccess(e) {
      if (e && e.length > 0) {
        this.ruleForm.fileName = e[0].fileName;
        this.ruleForm.fileUrl = e[0].fileUrl;
        this.ruleForm.fileList = e
          ? e.map((item) => {
              return {
                fileName: item.fileName,
                fileUrl: item.filePath,
                id: item.id,
              };
            })
          : [];
      } else if (e.length == 0) {
        this.ruleForm.fileList = [];
      }
    },
    // 确定
    handleDialogVisible(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("确定1:", this.ruleForm.tableData);
          this.$message({
            message: "操作成功",
            type: "success",
          });
        } else {
          console.log("error submit!!");
          console.log("确定:", this.ruleForm.tableData, this.fileList);
          return false;
        }
      });
    },
    // 点击上传文件
    handleUpload(val) {
      console.log("上传:", val.row.fileListTable);
      this.indexVal = val.$index;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.ruleForm.tableData[this.indexVal].fileListTable = [{}];
      this.ruleForm.tableData[this.indexVal].fileListTable[0].name =
        res.data[0].fileName;
      this.ruleForm.tableData[this.indexVal].fileListTable[0].url =
        res.data[0].fileUrl;
      this.ruleForm.tableData[this.indexVal].isDiaplay = "none";
      let divCon = document.getElementsByClassName("el-table__row");
      // 看看所有的表格中是否有已上传的(也就是长度不为0),如果已上传,则提示隐藏,否则提示存在
      let yichuan = null;
      this.$nextTick(() => {
        if (divCon.length > 0) {
          for (var i = 0; i < divCon.length; i++) {
            yichuan = divCon[i].children[0].getElementsByClassName(
              "el-upload-list__item"
            );
            if (yichuan.length != 0) {
              // 已经上传
              let errorDiv = divCon[i].children[0].getElementsByClassName(
                "el-form-item__error"
              )[0];
              if (errorDiv) {
                errorDiv.style.display = "none";
              }
              console.log("成功:", errorDiv);
            } else {
              // 未上传
            }
          }
        }
      });
    },
    handleDelete1(val) {
      this.ruleForm.tableData[val].fileListTable = [];
      this.ruleForm.tableData[val].isDiaplay = "block";
      // 如果点击了确定进行了所有的字段验证,则判断是否有超过表格长度的错误提示,如果有则进行全部验证
      let divCon1 = document.getElementsByClassName("el-form-item__error");
      if (divCon1.length > this.ruleForm.tableData.length * 2) {
        this.$refs["ruleForm"].validate((valid) => {});
      }
      let divCon = document.getElementsByClassName("el-table__row");
      // 看看所有的表格中是否有已上传的(也就是长度不为0),如果已上传,则提示隐藏,否则提示存在
      let yichuan = null;
      this.$nextTick(() => {
        if (divCon.length > 0) {
          for (var i = 0; i < divCon.length; i++) {
            yichuan = divCon[i].children[0].getElementsByClassName(
              "el-upload-list__item"
            );
            if (yichuan.length != 0) {
              // 已经上传
            } else {
              // 未上传
              let errorDiv = divCon[i].children[0].getElementsByClassName(
                "el-form-item__error"
              )[0];
              if (errorDiv) {
                console.log("回显");
                errorDiv.style.display = "block";
              }
            }
          }
        }
      });
    },
    // 新增列表
    handleAdd() {
      this.ruleForm.tableData.push({
        lon: "",
        fileListTable: [],
      });
    },
    // 删除
    handleDelete(indexValS, val) {
      if (this.ruleForm.tableData.length > 1) {
        this.ruleForm.tableData.splice(indexValS, 1);
      } else {
        this.$message({
          message: "至少上传一条数据",
          type: "warning",
        });
      }
      console.log("删除吭:", this.ruleForm.tableData);
    },
    //上传之前调用方法
    beforeUpload(file) {
      // 文件类型校验
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension =
        testmsg === "png" ||
        testmsg === "jpg" ||
        testmsg === "jpeg" ||
        testmsg === "mp4";
      if (!extension) {
        this.$message({
          message: "上传文件只能是.png、.jpg、.jpeg、.mp4格式!",
          type: "warning",
        });
      }
      return extension;
    },
    // 取消
    handleCancel() {
      this.dialogShow1 = false;
      this.$emit("close", this.dialogShow1);
    },
  },
};
</script>

<style lang="scss" scoped>
.newRecord {
  overflow: hidden;
  flex: 1;
  .danger-detail {
    flex: 1;
    display: flex;
    height: calc(100% - 15px);
    margin-top: 10px;
    .detail-left {
      height: 100%;
      width: 500px;
      background-color: white;
      padding: 20px;
      display: flex;
      flex-direction: column;
      .detail-text {
        flex: 1;
        overflow: auto;
      }
    }
    .detail-right {
      height: 100%;
      width: calc(100% - 463px);
      margin-left: 10px;
      background-color: white;
      padding: 20px;
      display: flex;
      flex-direction: column;
      .demo-ruleForm {
        margin-top: 20px;
        flex: 1;
        overflow: auto;
      }
      .dialog-footer {
        padding-top: 10px;
      }
    }
  }
}
::v-deep .el-upload__tip {
  line-height: 20px;
  margin-top: 0;
}
::v-deep .el-textarea__inner {
  height: 150px;
}
::v-deep .select-dian .el-form-item__content {
  display: flex;
}
::v-deep .select-dian .el-form-item__content .el-select {
  width: 100%;
  margin-right: 62px;
}
::v-deep .inputDian {
  display: flex;
  margin-left: 120px;
}
::v-deep .inputDian .input-rudian,
::v-deep .inputDian .input-rudian1 {
  width: 50%;
}
::v-deep .inputDian .input-rudian .el-form-item__content,
::v-deep .inputDian .input-rudian1 .el-form-item__content {
  margin-left: 0px !important;
}
::v-deep .inputDian .input-rudian1 {
  margin-left: 62px;
}
::v-deep .el-date-editor {
  width: 100%;
}
::v-deep .eventClass .el-select {
  width: 100%;
}
::v-deep .el-descriptions-item__content {
  text-align: right;
  display: block;
}
::v-deep .table-class .el-form-item__content {
  margin-left: 0 !important;
}
::v-deep .el-form-item__error {
  // width: 100%;
  // margin-left: -24px;
}
// ul {
//   list-style: none; //去掉标签默认的左边符号
//   // display: flex;
//   // flex-wrap: wrap;
// }
li {
  list-style-type: none; //去掉标签默认的左边符号
  // text-align: center;
  // width: 80%;
  margin: 0 auto;
  display: grid;
  grid-template-columns: calc(100% - 28px) 28px;
  align-items: center;
}
.el-link {
  display: block;
}
.el-icon-document {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  // width: 200px;
  display: block;
  height: 20px;
  line-height: 20px;
  text-align: left;
}
</style>

fileUpload1组件:引入到文件中

<template>
  <div class="upload-file">
    <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" drag :file-list="fileList" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers" :data="{ bucketName }" class="upload-file-uploader" ref="fileUpload">
      <!-- 上传按钮 -->
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
        的文件
      </div>
    </el-upload>

    <!-- 文件列表 -->
    <!-- <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul"> -->
    <li class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList" :key="index+1">
      <el-link :href="`${baseUrl}${file.filePath}`" :underline="false" target="_blank">
        <span class="el-icon-document"> {{ file.fileName }} </span>
      </el-link>
      <div class="ele-upload-list__item-content-action">
        <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
      </div>
    </li>
    <!-- </transition-group> -->
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    // 每个功能的上传存储位置不同 该参数见字典file_upload或问对应后端
    bucketName: {
      type: String,
      default: "gas",
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/base/minio/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件,请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败,请重试");
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList = res.data;
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.fileList);
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.fileList);
        // this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
  },
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.el-upload-list__item {
  display: flex;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-left: 10px;
  margin-right: 10px;
}
</style>

你可能感兴趣的:(vue.js,前端,javascript)