element upload 上传图片 单独上传 和 添加formdata中提交的rules验证

element upload上传图片rules的验证分为单独提交还是放入formdata中提交

一个前端小菜鸡。若下边的内容有瑕希望告诉我,如果有更好的方法希望告诉我,感谢万分。

这篇文章主要介绍的对el-upload放在表单中提交之前rules的验证。这里的图片是必须提交项如果可以不提交可用常用方法直接提交就可以。

放在formadata表达中提交

<el-form ref="personform" label-position="right" label-width="120px" :model="formLabelAlign" status-icon :rules="rules">
        <el-row>
          <el-form-item label="简述">
            <el-input type="textarea" v-model="formLabelAlign.paper" autocomplete="off"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="file" ref="uploadpic">
            <el-upload
              style="display:inline-block"
              :limit="2"
              class="upload-demo"
              ref="upload"
              action="/hqx/knowledge/importKnowledge"
              :before-upload="beforeAvatarUpload"
              :auto-upload="false"
              :on-change="imageChange"
              :on-remove="imageRemove"
            >
              <el-button slot="trigger" size="small" type="primary" plain>上传</el-button>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
 <script>
	import _ from "lodash";
	export default {
	  data() {
	    return {
	      xiugai: false,
	      formLabelAlign: {
	        paper: ""
	      },
	      images: [],// 图片存储
	      rules: {
	        file: [{ required: true, message: "请上传图片", trigger: "change" }]
	      },
	      haspic: false // 默认没有传图片
	    };
	  },
	  methods: {
	    beforeAvatarUpload(file) {
	      // 文件类型进行判断
	      const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
	      const isLt2M = file.size / 1024 / 1024 < 2;
	      if (!isJPG) {
	        this.$message.error("上传图片只能是 image/jpeg/png 格式!");
	      }
	      if (!isLt2M) {
	        this.$message.error("上传图片大小不能超过 2MB!");
	      }
	      return isJPG && isLt2M;
	    },
	    imageChange(file, fileList, name) {//on-change触发
	      this.images["file"] = fileList;
	      this.haspic = true;
	      // 如果上传了就不显示提示图片警告
	      if (typeof this.images.file != "undefined") {
	        if (this.images.file.length > 0) {
	          this.$refs["uploadpic"].clearValidate();
	        }
	      }
	    },
	    imageRemove(file, fileList, name) { //on-remove触发
	    //如果images为空了说明并没有提交图片所以需要显示警告
	      if (typeof this.images.file != "undefined") {
	        if (this.images.file.length > 0) {
	          this.$refs["uploadpic"].clearValidate();
	        } else {
	          this.$refs["uploadpic"].validate();
	          this.haspic = false;
	        }
	      }
	    },
	    confirm() {// 提交绑定的事件
	      if (this.haspic) {
	        // 去掉rules中对图片的验证
	        _.unset(this.rules, ["file"]);
	        this.$refs["personform"].validate(valid => {
	          if (valid) {
	            console.log("说明已经添加了图片直接提交就行了");
	            const wfForm = new FormData();
	              wfForm.append( 'dsc',this.formLabelAlign.paper)
	              Object.entries(this.images).forEach(file => {
	                  file[1].forEach(item => {
	                  wfForm.append('files', item.raw)
	                  wfForm.append(item.name, file[0])
	                  })
	              })
	              // 直接提交
	          } else {
	            console.log("error submit!!");
	            return false;
	          }
	        });
	      } else {
	        // 向rules提价一条对图片的验证。
	        _.set(this.rules, "file", { required: true, message: "请上传图片", trigger: "change"});
	        this.$refs["personform"].validate(valid => {
	          if (valid) {
	            console.log("说明图片没有提交");
	          } else {
	            console.log("error submit!!");
	            return false;
	          }
	        });
	      }
	    }
	  }
	};
</script>

下边解释一下每段代码的含义:
1.

imageChange(file, fileList, name) {//on-change触发
	      this.images["file"] = fileList;
	      this.haspic = true;
	      // 如果上传了就不显示提示图片警告
	      if (typeof this.images.file != "undefined") {
	        if (this.images.file.length > 0) {
	          this.$refs["uploadpic"].clearValidate();
	        }
	      }
	    }

if (typeof this.images.file != “undefined”) 这个可加可不加
其中的一个原因是因为要频繁对rules进行操作因为element的el-upload的提示功能在选择了图片的时候并不会对图片的提示进行更改所以只能自己进行操作更改他显示或者隐藏
haspic是用来记录他是否上传了图片 如果上传为true否则为false 在后面提交的时候有用。
2.考虑到用户可能会选择了图片又删除了所以加上了一个判断
如果在提交的时候进行验证或者不考虑用户全部删除显示提示可不加

imageRemove(file, fileList, name) { //on-remove触发
	    //如果images为空了说明并没有提交图片所以需要显示警告
	      if (typeof this.images.file != "undefined") {
	        if (this.images.file.length > 0) {
	          this.$refs["uploadpic"].clearValidate();
	        } else {
	          this.$refs["uploadpic"].validate();
	          this.haspic = false;
	        }
	      }
	    },
confirm() {// 提交绑定的事件
	      if (this.haspic) {
	        // 去掉rules中对图片的验证
	        _.unset(this.rules, ["file"]);
	        this.$refs["personform"].validate(valid => {
	          if (valid) {
	            console.log("说明已经添加了图片直接提交就行了");
	            const wfForm = new FormData();
	              wfForm.append( 'dsc',this.formLabelAlign.paper)
	              Object.entries(this.images).forEach(file => {
	                  file[1].forEach(item => {
	                  wfForm.append('files', item.raw)
	                  wfForm.append(item.name, file[0])
	                  })
	              })
	              // 直接提交
	          } else {
	            console.log("error submit!!");
	            return false;
	          }
	        });
	      } else {
	        // 向rules提价一条对图片的验证。
	        _.set(this.rules, "file", { required: true, message: "请上传图片", trigger: "change"});
	        this.$refs["personform"].validate(valid => {
	          if (valid) {
	            console.log("说明图片没有提交");
	          } else {
	            console.log("error submit!!");
	            return false;
	          }
	        });
	      }
	    }
	  }
	};

提交的时候进行判断。因为没有想到其他的方法所以写了一个变量判断是否在rules加上对图片的判断。因为如果存在对图片的判断。form验证的时候就总是throw error 不能进行提交操作this.$refs[“personform”].validate(valid){}是提交form表单的时的验证
(1)在有图片的时候去掉对图片的验证
(2)在有图片的时候加上对图片的验证

不放在formdata中提交(相对于上一个这个简单多了)

<template>
  <div>
      <el-form ref="personform" label-position="right" label-width="120px" :model="formLabelAlign" status-icon :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布人">
              <el-input
                size="mini"
                v-model="formLabelAlign.person"
                autocomplete="off"
                clearable
                :disabled="xiugai"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="简述">
            <el-input type="textarea" v-model="formLabelAlign.paper" autocomplete="off"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="file" ref="uploadpic">
            <el-upload
              style="display:inline-block"
              :limit="2"
              class="upload-demo"
              ref="upload"
              action="/hqx/knowledge/importKnowledge"
              :before-upload="beforeAvatarUpload"
              :auto-upload="false"
              :on-change="imageChange"
              :on-remove="imageRemove"
              :on-success="onsuccess"
            >
              <el-button slot="trigger" size="small" type="primary" plain>上传</el-button>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
  </div>
</template>
<script>
import _ from "lodash";

export default {
  data() {
    return {
      xiugai: false,
      formLabelAlign: {
        paper: ""
      },
      images: [],
      rules: {
        file: [{ required: true, message: "请上传图片", trigger: "change" }]
      },
      haspic: false // 默认没有传图片
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      // 文件类型进行判断
      const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 image/jpeg/png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    imageChange(file, fileList, name) {
      this.images["file"] = fileList;
      this.haspic = true;
      // 如果上传了就不显示提示
      if (typeof this.images.file != "undefined") {
        if (this.images.file.length > 0) {
          this.$refs["uploadpic"].clearValidate();
        }
      }
    },
    imageRemove(file, fileList, name) {
      if (typeof this.images.file != "undefined") {
        if (this.images.file.length > 0) {
          this.$refs["uploadpic"].clearValidate();
        } else {
          this.$refs["uploadpic"].validate();
          this.haspic = false;
        }
      }
    },
    onsuccess(response, file, fileList){
      //  如果提交失败将haspic改为false后边的数据就不让他提交
    },
    confirm() {
      if (this.haspic) {
        // 去掉rules中对图片的验证
        _.unset(this.rules, ["file"]);
        this.$refs["personform"].validate(valid => {
          if (valid) {
            console.log("说明已经添加了图片直接提交就行了");
            const wfForm = new FormData();
              wfForm.append( 'dsc',this.formLabelAlign.paper)
              //直接将wfForm提交就可以
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
       alert('请添加图片之后在提交')
      }
    }
  }
};
</script>
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lbchenxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值