antd 上传限制大小和文件类型

效果图:

<a-upload-dragger
              name="file"
              action="上传的接口"
              @change="uploadHandleChange" //上传文件改变时的状态
              :before-upload="beforeUpload" //上传文件之前的钩子
              :file-list="fileList" //已经上传的文件列表(受控)
            >
              <p class="ant-upload-drag-icon">
                <img
                  class="img"
                  src="@/assets/image/crowd-tags/upload.png"
                  alt=""
                />
              </p>
              <p class="ant-upload-text">
                点击或将文件拖拽到这里上传
              </p>
            </a-upload-dragger>

 

data(){
    return{
        fileList: [
        // {
        //   uid: '1',
        //   name: '导入模板',
        //   status: 'done',
        //   url: 'http://www.baidu.com/yyy.png',
        // },
      ],
    }
}

 

// 上传文件改变时的状态
    beforeUpload(file, fileList) {
      return new Promise((resolve, reject) => {
        const isSize = file.size / 1024 / 1024
        const isExcel =
          file.type ===
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.type === 'xlsx' ||
          file.type === 'application/vnd.ms-excel'
        if (isSize > 20) {
          this.$message.error('文件大小不可超过20M')
          return false
        }
        if (!isExcel) {
          this.$message.error('只支持上传excel文件')
          return false
        }
        resolve(true)
      })
    },

 

//上传文件之前的钩子
    uploadHandleChange(info) {
      let { fileList } = info
      if (info.file.status !== 'uploading') {
        if (info.fileList.length > 1) {
          //限制只上传一个文件,再次上传时则替换(覆盖)以前的文件
          info.fileList.splice(0, 1)
        }
          //info.file.response  这个是后端接口返回的数据
        // 文件上次格式错误
        if (info.file.response.res != 0) {
          this.$message.error(info.file.response.msg)
          this.fileList = []
          return
        }
      }
      if (info.file.status === 'done') {
        
      } else if (info.file.status === 'error') {
        this.$message.error('上传失败')
      }
      this.fileList = [...fileList] //重点
    }

 

posted @ 2023-05-08 10:45  Private!  阅读(1521)  评论(0编辑  收藏  举报