1. 在el-upload控件中加入on-change方法:

<el-upload id="file"
  ref="upload"
  slot="append"
  :action="file.action"
  :with-credentials="true"
  name="file"
  :data="file.data"
  :show-file-list="false"
  accept=".xls,.xlsx,.csv"
  :disabled="isDisabled"
  :auto-upload="false"
  :on-change="handleChangeFile">
  <el-button class="file_upload"
    type="default"></el-button>
  <label for="file"
    class="file-btn h-icon-folder"></label>
</el-upload>

2. 在on-change方法中处理:

handleChangeFile (file, fileList) {
  this.isDisabled = false
  if (!file) return
  var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
  const isLt2M = file.size / 1024 / 1024 < 50
  if (testmsg !== 'xls' && testmsg !== 'xlsx' && testmsg !== 'csv') {
    this.$refs.upload.clearFiles()
    this.$message({
      message: '上传文件只能是 .xls、.xlsx、csv格式!',
      type: 'warning'
    })
    return false
  }
  if (!isLt2M) {
    this.$refs.upload.clearFiles()
    this.$message({
      message: '上传文件大小不能超过 50MB!',
      type: 'warning'
    })
    return false
  }
  this.fileName = file.name
}

3.作为补充, 如果对图片的尺寸有限制也可以实现的(这里只做补充, 此文件中没用到):

// 说明: 这部分代码不是本项目的,扩展
onchange (file) {
  let isLt = file.size / 1024 < 200 // 判断是否小于200Kb
  if (!isLt) {
    this.$message.warning('图片大小不能超过200KB! 请重新上传')
    this.$refs.upload.clearFiles()
    this.basicForm.image = ''
    this.basicForm.imageFile = []
  } else {
    this.asyncImgChecked(file).then(data => {
      if (data) {
        this.basicForm.image = file.name
        this.basicForm.imageFile = file
      } else {
        this.basicForm.image = ''
        this.basicForm.imageFile = []
        this.$refs.upload.clearFiles()
        this.$message.warning('图片尺寸不小于64 X 64')
      }
    })
  }
},
// 计算图片尺寸
asyncImgChecked (file) {
  return new Promise((resolve) => {
    let reader = new FileReader()
    reader.readAsDataURL(file.raw) // 必须用file.raw
    reader.onload = () => { // 让页面中的img标签的src指向读取的路径
      let img = new Image()
      img.src = reader.result
      // console.log(`1当前文件尺寸大小:${img.width}×${img.height}`)
      if (img.complete) { // 如果存在浏览器缓存中
        if (img.width < 64 || img.height < 64) {
          resolve(false)
        } else {
          resolve(true)
        }
      } else {
        img.onload = () => {
          if (img.width < 64 || img.height < 64) {
            resolve(false)
          } else {
            resolve(true)
          }
        }
      }
    }
  })
}

Logo

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

更多推荐