先看html部分 :

<el-upload
  class="avatar-uploader"
  action=""
  accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif"
  :http-request="uploadImg"
  :before-upload="beforeAvatarUpload"
  :show-file-list="false"
  list-type="picture"
>
  <img v-if="mergeData.url" :src="mergeData.url" class="avatar" />
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  <div slot="tip" class="el-upload__tip">
     格式支持jpg、gif、png、jpeg,且不超过5M,图片尺寸需为744*208
  </div>
</el-upload>

 js部分:

beforeAvatarUpload(file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传图片只能是jpg、gif、png、jpeg格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return false
      }
      const isSize = new Promise(function (resolve, reject) {
        const width = 744 // 限制图片尺寸为744x208
        const height = 208
        const URL = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function () {
          const valid = img.width === width && img.height === height
          valid ? resolve() : reject()
        }
        img.src = URL.createObjectURL(file)
      }).then(
        () => {
          return file
        },
        () => {
          this.$message.error('图片不规范,请按要求上传')
          return Promise.reject()
        }
      )
      return isJPG && isLt2M && isSize
},

Logo

前往低代码交流专区

更多推荐