vue中限制图片宽高相等再上传,upload ui组件限制图片宽高相等

本文介绍了一种基于Vue的图片上传组件的beforeUpload方法,该方法确保只有大小小于5MB且格式为JPG或PNG的图片才能上传。当图片类型需要宽高相等时,会进一步检查图片尺寸。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

结合upload组件

// imgType ==8时,要求图片宽高相等才可以上传
    beforeUpload(file) {
      let that = this
      const isLt5M = file.size / 1024 / 1024 < 5
      const allowedFileType =
        file.type.indexOf('jpg') !== -1 || file.type.indexOf('png') !== -1 || file.type.indexOf('jpeg') !== -1
      if (!allowedFileType) {
        this.$message.error('请上传正确的图片格式!')
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!')
      }
      let whsize = true
      let promise = ''
      if (this.imgType == 8) {
      return new Promise((resolve, reject) => {
          const img = new Image()
          const reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = function() {
            // 读取到的文件内容.这个属性只在读取操作完成之后才有效,并且数据的格式取决于读取操作是由哪个方法发起的.所以必须使用reader.onload,
            const url = reader.result
            // reader读取的文件内容是base64,利用这个url就能实现上传前预览图片
            img.src = url
          }
          img.onload = function() {
            const width = img.width
            const height = img.height
            console.log(width, height)
            if (width != height) {
              whsize = false
              that.$message.error('请按照尺寸比例要求上传图片!')
              reject()
            } else {
              if(allowedFileType && isLt5M){
                resolve(file)
              }
            }
          }
        })
      }
      if (that.imgType != 8) {
        return allowedFileType && isLt5M
      } 
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值