美文网首页大前端前端开发那些事儿
elementUI上传图片前判断图片的尺寸大小

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

作者: 冷r | 来源:发表于2020-07-11 16:43 被阅读0次

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

    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上传图片前判断图片的尺寸大小

        本文链接:https://www.haomeiwen.com/subject/hhuicktx.html