input方式上传文件并且本地预览&&图片校验

输入框: 

  <input
            class="btn-upload"
            type="file"
            name="file"
            accept="image/jpg, image/png, image/jpeg"
            @change="$emit('handleInsertCapture',$event,item,'new')"
          />

 input点击方法选择文件:并渲染到<img src>的src中

/**
     * 新增图片
     */
    handleInsertCapture($event, item,type) {
          let file = $event.target.files[0];
          if (!this.checkImg(file)) {
            return;
          }
          const reader = new FileReader()
          reader.onload = (e) => {
            this.form.urlPath = e.target.result
          }
          reader.readAsDataURL(file)
          this.file = file
    },

图片校验:file:文件流 || 文件对象

  /**
     * 图片校验
     */
    checkImg(file) {
      const isJPG = file.type === "image/jpg";
      const isJPEG = file.type === "image/jpeg";
      const isPng = file.type === "image/png";
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isJPG && !isPng && !isJPEG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt1M) {
        this.$message.error("上传图片大小不能超过 1M!");
        return false;
      }
      return true;
    },

图片上传:写在弹窗确认按钮上随便写个按钮触发你的接口就行。参数方式为:x-www-form-urlencoded所以用new FormData()了

 let formData = new FormData();
   formData.append("file", this.file);
 上传接口xxx(formData).then(res=>{
                  if(res.code === 200){
                    this.$message.success('保存成功')
                    this.$emit('clear')
                  }
                }).catch(err=>{
                  this.$message.error(err)
                })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值