需求: 

上传图片的格式为:.jpg、.jpeg、.png

大小为:1M以内

尺寸为:400*400

代码实现: 

直接拿的elementui官网的html代码,加了一句:accept="image/jpg,image/jpeg,image/png"

<el-upload
  class="avatar-uploader"
  action="https://jsonplaceholder.typicode.com/posts/"
  accept="image/jpg,image/jpeg,image/png"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

下面是写在methods里的js代码: 

// 限制图片尺寸
    limitFileWH(E_width, E_height, file) {
      const _this = this
      let imgWidth = ''
      let imgHight = ''
      const isSize = new Promise(function(resolve, reject) {
        const width = E_width
        const height = E_height
        const _URL = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function() {
          imgWidth = img.width
          imgHight = img.height
          const valid = img.width === width && img.height === height
          valid ? resolve() : reject()
        }
        img.src = _URL.createObjectURL(file)
      }).then(() => {
        return true
      }, () => {
        _this.$message.warning({
          message: '上传图片的尺寸应为' + E_width + '*' + E_height + ',当前上传图片的尺寸为:' + imgWidth + '*' + imgHight,
          btn: false
        })
        return false
      })
      return isSize
    },

    // 图片上传之前的判断
    handleBeforeUpload(file) {
      return new Promise((resolve, reject) => {
        const suffix = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
        const isLt1M = file.size / 1024 / 1024 < 1
        if (!suffix) {
          this.$message.error('只能上传图片!')
          return reject(false)
        }
        if (!isLt1M) {
          this.$message.error('上传图片大小不能超过 1MB!')
          return reject(false)
        }
        // 调用[限制图片尺寸]函数
        this.limitFileWH(400, 400, file).then((res) => {
          file.isFlag = res
          if (file.isFlag) {
            return resolve(true)
          } else {
            return reject(false)
          }
        })
      })
    },
// 上传成功的回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },

上传的图片不符合需求的会提示错误信息,停止上传。 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐