el-upload自定义上传文件时需要显示进度条,但使用http-request会覆盖默认的上传行为,on-progress也就不生效了,所以可以自定义上传的实现

效果图

在这里插入图片描述

功能实现

按钮
<el-upload class="upload-demo" drag action="" multiple accept=".xls,.xlsx" :show-file-list="false" :http-request="uploadFile" :before-upload="beforeUpload">
   <i class="el-icon-upload"></i>
   <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
 </el-upload>
 
 //进度条
 <el-progress v-if="showProgress" :percentage="percentage"></el-progress>
数据
data() {
    return {
    	showProgress:false,
    	percentage:0
    }
}
事件
beforeUpload(file) {
   const isLimit = file.size / 1024 / 1024 < 10;
   if (!isLimit) {
     this.$message.error('文件不能超过10M!');
     return
   }
 },
 
  //上传excel
  async uploadFile(params) {
    let fileFormat = params.file.name.toLowerCase().split(".").splice(-1)[0];
    if (fileFormat !== 'xls' && fileFormat !== 'xlsx') {
      this.$message.error('文件类型不正确!');
      return
    }
    const _file = params.file;
    this.showProgress = true;
    // 前端解析显示
    const fileReader = new FileReader();
    fileReader.onload = (ev) => {
      try {
        const data = ev.target.result;
        const workbook = XLSX.read(data, {
          type: 'binary',
          cellDates: true
        });
        // 取第一个key的值
        let key = this.getFirstAttr(workbook.Sheets);
        //excel中的字段无值时默认为空
        const sheet2JSONOpts = { defval: "" };
        // 取到数组
        const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[key], sheet2JSONOpts);
        // 赋值
        if (!this.isEmpty(sheetArray)) {  //判断上传文件是否为空的方法,自己写就行
          //进度条处理(重点)
          const uploadEvent = (progressEvent) => {
            this.percentage = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(0));
          };

          // 后端传file类型
          let form = new FormData();
          form.append("multipartFile", params.file);
		  // 导入接口
          this.importCheck(form, uploadEvent)   //uploadEvent需放在axios请求头headers里面
        } else {
          this.showProgress = false;
          this.$message.error('文件无数据,请重新上传');
          return
        }
      } catch (e) {
        this.$message.error('文件类型不正确!');
      }
    };
    fileReader.readAsBinaryString(_file);
  },

导入接口

 async importCheck(params, uploadEvent) {
      let res = await this.$http.costDetail.costDetailImportCheck(params, uploadEvent); // 此处是自己项目封装的api
      if (res.code === "200") {
        //逻辑处理省略
        this.showProgress = false;
      } else {
        this.showProgress = false;
      }
    },

接口方法

costDetailImportCheck: function (data,uploadEvent) {
        return instance.api('baEquipmentCost/checkExcel', 'post', data,'','',uploadEvent)
 },

uploadEvent——在封装的axios请求方法的headers里面加入即可(关键)

在这里插入图片描述

Logo

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

更多推荐