当前位置 博文首页 > lllomh的博客:elementUI 限制上传图片尺寸

    lllomh的博客:elementUI 限制上传图片尺寸

    作者:[db:作者] 时间:2021-07-10 09:41

    先定义方法

        //限制图片尺寸
        limitFileWH(E_width, E_height, file) {
          let _this = this;
          let imgWidth = "";
          let imgHight = "";
          const isSize = new Promise(function(resolve, reject) {
            let width = E_width;
            let height = E_height;
            let _URL = window.URL || window.webkitURL;
            let img = new Image();
            img.onload = function() {
              imgWidth = img.width;
              imgHight = img.height;
              let valid = img.width == width && img.height == height;
              valid ? resolve() : reject();
            }
            img.src = _URL.createObjectURL(file);
          }).then(() => {
            return true;
          }, () => {
            _this.$message.warning({
              message: '上传文件的图片大小不合符标准,宽需要为' + E_width + 'px,高需要为' + E_height + 'px。当前上传图片的宽高分别为:' + imgWidth + 'px和' +
                imgHight + 'px',
              btn: false
            })
            this.$refs.upload.clearFiles();
            this.fileList=''
            return false;
          });
          return isSize
        },

    再定义方法 给上传前钩子调用

        beforeAvatarUpload(file){
          //调用[限制图片尺寸]函数
          this.limitFileWH(1220, 500, file).then((res) => {
            console.log(res)
            file.isFlag = res
          })
        },

    最后说下 正常限制文件大小宽高尺寸都应该在?

    :before-upload="beforeAvatarUpload"

    里面去设置的: 这里有个坑 就是 如果你的?:auto-upload="false" 那这个钩子就不会执行 true 才行

    cs