Vue使用Element UI 的upload做Excel文件上传,后端拿到Excel做数据导入

首先呢,我的需求是用Excel表做数据导入,前端传入文件,后端拿到文件解析,然后插入数据库,由于对vue不熟悉,踩了很多的坑,最后还是做完了,这里分享一下我踩过的坑。
直接贴代码吧:
<!--文件导入-->
    <template>
      <div>
        <el-upload
          class="filter-item"
          name="file"
          action="string"
          :on-error="uploadFalse"
          :on-success="uploadSuccess"
          :before-upload="beforeAvatarUpload"
          :limit="1"
          ref="upload"
          accept=".xlsx,.xls"
          :show-file-list="false"
          :file-list="fileList"
          :http-request="uploadFile"
        >
          <el-button  style="margin-left: 10px;" icon="el-icon-edit" type="primary" v-has-perm="">商品上架</el-button>
        </el-upload>
      </div>
    </template>

最初,我在action里直接添加了后台的API地址,但是拿不到file文件。
然后去查了很多帖子,把目光转到 :http-request="uploadFile"这个属性上面,
在这里插入图片描述
在这里插入图片描述

action给了一个string值,http-request属性覆盖默认的上传行为,可以自定义上传的实现,从param.file可以直接拿到上传的file文件,拿到文件才能去传输,upload方法:

    async uploadFile(param){
      const File = param.file;
      let formData1 = new FormData();
      formData1.append("file", File);
      await obj.ExcelInsertGoodinStore(formData1);
      this.findPage();
    },

ExcelInsertGoodinStore方法:你可以有自己的写法

ExcelInsertGoodinStore(entity){
    return axios.post(`good/ExcelInsertGoodinStore`,entity)
  }

其他的钩子函数:
上传成功,上传失败,以及上传校验
在这里插入图片描述

 async uploadSuccess(response, file, fileList) {
      console.log(response)
      if (response.status==20000) {
        this.$message({
          message: response.message,
          type: 'success'
        });
      } else {
        this.$message({
          message: response.message,
          type: 'error'
        });
      }
    },
    uploadFalse(response, file, fileList) {
      this.$message({
        message: '文件上传失败!',
        type: 'error'
      });
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload(file) {
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        this.$message({
          message: '上传模板只能是 xls、xlsx格式!',
          type: 'error'
        });
      }
      if (!isLt2M) {
        console.log("上传模板大小不能超过 10MB!");
        this.$message({
          message: '上传模板大小不能超过 10MB!',
          type: 'error'
        });
      }
      return extension || extension2 || extension3 || (extension4 && isLt2M);
    },

后台代码:
很多帖子里会说name方法要与后台接收的参数一致,我一直都写一致的,所以也没发现报错,name=“file” 和后台接收写一致就好了,接收我是用MultipartFile 直接接收,怎么解析(这里就不写了),解析也有很多帖子

 /**
     * 商品批量导入功能
     */
    @RequestMapping(value = "/ExcelInsertGoodinStore", method = RequestMethod.POST)
    @ResponseBody
    public AxiosResult importGood(@RequestParam("file") MultipartFile file) {
        BaseGoodService.GoodImport(file);
        return AxiosResult.success(AxiosStatus.OK);
    }

这样基本上就可以了,至于你要保存文件到什么地方,还是做文件解析,根据需求来吧。
在这里插入图片描述

Vue项目中,使用Element UI的`el-upload`组件来上传Excel文件时,前端主要负责文件的选择和预处理。当用户选择文件后,`onUploadChange`方法会被触发。在这个方法里,你会检查文件类型,如果是`.xls`格式(通过判断raw.type),才会继续操作。例如: ```javascript // 前端处理文件 onUploadChange(file) { // 检查文件类型 if (!/(application/vnd.ms-excel)/i.test(file.raw.type)) { this.$message.error('上传文件只能是.xls格式!'); return; } // 使用FileReader读取文件内容 const reader = new FileReader(); reader.readAsArrayBuffer(file.raw); reader.onload = (e) => { // 这里e.target.result是文件的内容,可以传递给后端 }; } ``` 在`submitUpload`方法中,你可以将读取到的原始文件内容以`FormData`的形式发送到后端Java后端通常会解析这个`multipart/form-data`请求体来获取上传Excel文件。以下是一个简单的概念性Java代码片段,用于说明如何从Spring MVC控制器接收并处理这种请求: ```java @PostMapping("/VehicleManagement/upload/oilCardInfoUpload") public ResponseEntity<String> uploadOilCardInfo(@RequestParam("oilCardInfoExcel") MultipartFile excelFile) throws IOException { byte[] fileBytes = excelFile.getBytes(); // 进一步处理文件内容,比如读取Excel数据 // ... // 返回响应结果 return ResponseEntity.ok("文件接收"); } ``` 在Java中,`MultipartFile`接口提供了读取文件的方法,如`getBytes()`,用来获取整个文件的内容。然后,你可以使用Apache POI库或者其他Excel解析库来处理这些数据
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值