elementUI上传图片前判断图片的尺寸大小

在上传图片前判断尺寸的大小,遇到了好多的坑。

1.没有注意到onload是异步加载,所以一定要在onload后在执行判断图片尺寸

2.upload内部需要一个promise,简单的return出false并没有什么用


image.png

完整代码如下:

  beforeUpload(file) {
      const _URL = window.URL || window.webkitURL
      const isSize = new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = function() {
          this.width > 500 ? reject() : resolve()
        }
        img.src = _URL.createObjectURL(file)
      }).then(
        () => {
          return file
        },
        () => {
          this.$message({
            type: 'error',
            message: '图片宽度不能超过500'
          })
          return Promise.reject()
        }
      )
      return isSize
    }

你可能感兴趣的:(elementUI上传图片前判断图片的尺寸大小)