1.在el-upload控件中加入方法:


//accept="image/*"  进行图片类型的限制
<el-upload ref="refUpload" :action="upload()" accept="image/*" :show-file-list="false" :on-success="fileSuccess" :on-progress="fileProgress">
   <img v-if="ruleForm.previewAddressUrl":src="ruleForm.previewAddressUrl" class="avatar">
   <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

2.在api文件引用接口

export function UploadViewIma() {
  return //接口地址
}

3.在方法中处理:

import { UploadViewIma } from "接口所在地址" 
<script>
 data() {
    return {
      ruleForm:{
          previewAddressUrl:""
      }
    }
 },
 methods: {
    //返回上传地址
    upload() {
      return UploadViewIma();
    },
    //图片格式校验
    fileProgress(event, file, fileList) {
      let isImage = file.raw.type.includes("image");
      if (!isImage) {// 检查文件类型
        this.$message.error("预览图须是图片类型!");
        this.$refs.refUpload.abort();
      }
      let fileSize = parseInt(file.size / 1024) <= 500;
      if (!fileSize) {// 检查文件大小
        this.$message.error(`预览图大小不能超过500kB! 请重新上传`);
        this.$refs.refUpload.abort();
      }
      if (isImage == true && fileSize == true) {
        new Promise((resolve, reject) => {
          const img = new Image();
          img.src = window.URL.createObjectURL(file.raw);
          img.onload = () => {
            if (img.width > 368 && img.height > 228) {
              // 处理尺寸超过限制的情况 这里是建议所以只是提示,依然是通过的
              this.$message('建议上传图片为 368 X 224');
              resolve();
            } else {
              // 尺寸符合要求,可以继续上传
              resolve();
            }
          };
        });
      }
    },
    //图片回显
    fileSuccess(res, file, fileList) {
      this.ruleForm.previewAddressUrl = res.data;
    },
}
</script>

Logo

前往低代码交流专区

更多推荐