element-ui文件上传使用

<el-upload
          ref="uploadRef"                //给上传文件绑定一个ref必要时好清空上传文件数组
          style="margin-left:10px"
          :limit="limitNum"               //限制上传文件个数  这里我一个对象来代替
          action=""                           // 上传地址 
          multiple                              
          :auto-upload="false"          //自动上传文件
          :show-file-list="false"         //是否显示上传信息列表
          class="upload-demo"        // 关闭前的验证
          :before-upload="beforeUploadFile"    //上传前的验证
          :on-exceed="exceedFile"     //超出上传个数的验证
          :on-change="fileChange"     //上传文件发生改变时触发change事件
        >
          <el-button slot="trigger" type="primary">导入文件</el-button>
</el-upload>

——-----------------------------------------------------------------------------------------

 fileChange(file, fileList) {
      this.beforeUploadFile(file)
      if (this.beforeUploadFile(file)) {
        this.$refs.uploadRef.clearFiles()
        this.fileList.push(file.raw)
        this.uploadFile()
      } else {
        return this.$refs.uploadRef.clearFiles()      //清空上传列表里面的数据
      }
    }

    // 文件超出个数限制时的钩子
exceedFile(files, fileList) {
      this.$message.warning(`只能选择 ${this.limitNum} 个文件,当前共选择了 ${files.length + fileList.length} 个`)
    }

    // 上传之前进行处理
 beforeUploadFile(file) {
      const isLt5M = file.size / 1024 / 1024 < 10
      if (this.allowType.indexOf(file.name.substring(file.name.lastIndexOf('.') + 1)) === -1) {
        this.$message.error({ title: '系统提示', message: `上传文件只能是 ${this.allowTypeTips} 格式!` 
      })
        return false
      }
      if (!isLt5M) {
        this.$message.error({ title: '系统提示', message: '上传文件大小不能超过 10MB!' })
        return false
      } else {
        return true
      }
    }

    // 上传文件
uploadFile() {
      if (this.fileList.length === 0) {
        this.$message.warning('请选择文件')
      } else {
        var file = new FormData()
        file.append('file', this.fileList[0])
        getBudgetUpload(file).then((res) => {
          if (res.code === 0) {
            this.totalPage = res.data.list.length
            this.tableData = res.data.list
            this.$message.success({ title: '系统提示', message: '上传成功' })
            this.fileList = []
          } else {
            this.$message.error({ title: '系统提示', message: '上传失败' })
          }
        })
      }
    },
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容