Java相关

Vue + SpringBoot 上传 Excel 文件

2022-01-24  本文已影响0人  思念_似水流年

Vue 前端

  1. 将上传按钮做成一个 Vue 组件 upload-btn.vue。
    具体做法是:在 src/components 目录下新建一个 公共组件 UploadBtn,代码如下:
<template>
  <el-button
    v-bind="$attrs"
    @click="handleUpload">
    <slot />
    <input
      type="file"
      ref="file"
      :accept="accept"
      style="visibility: hidden; width: 1px; height: 1px; vertical-align: middle;"
      @change="handleFile"
    >
  </el-button>
</template>

<script>
export default {
  props: {
    accept: {type: String}
  },
  methods: {
    handleUpload () {
      this.$refs.file.click()
    },
    handleFile (e) {
      const file = e.target.files[0] // 获得文件对象
      e.target.value = '' // 重置 input 的 value,否则下次选择同一个文件时不会触发 change 事件。
      // do upload
      // 为了组件的通用,本组件不负责上传,交由上层处理
      this.$emit('upload', file)
    }
  }
}
</script>
  1. 页面调用该组件上传文件
    Step1:插入触发按钮
<upload-btn
    size="small"
    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
    @upload="handleUpload"
    >批量上传</upload-btn>

Step2:引用组件,指定上传方法

import UploadBtn from '@/components/UploadBtn'

export default {
  components: {
    UploadBtn
  },
  methods: {
    handleUpload (file) {
      // https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/append
      const form = new FormData();
      form.append("file", file, file.name);
      // 如果在上传文件的同时,还要提交更多的信息,就像下面这样写
      // form.append("key1", "value");
      // 设置文件上传的请示头
      //const requestConfig = {
      //  headers: {
     //     'Content-Type': 'multipart/form-data'
     //   }
    //  };
      // 使用 axios 上传文件
      uploadFile( form).then(resp => {
          this.$notify.success(resp.msg)
          this.fetchBrandList()
      });
    }
  }
}

这里对 axios 做了封装,可以直接调用 api 中对应的方法:

import request from '@/utils/request'

export function uploadFile(data) {
  return request({
    method: 'post',
    url: '/mobile/brand/uploadFile',
    data,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

SpringBoot 后端

Controller 层接收请求:

@RestController
@RequestMapping("/mobile")
public class MobileFilterController {
    @Autowired
    private MobileBrandService mobileBrandService;

    @PostMapping("/brand/uploadFile")
    public Response uploadFile(MultipartFile file) throws IOException {
        // 解析上传的 Excel 文件
        Response<List<MobileBrandManagement>> response = mobileBrandService.getExcelData(file);
        if (!response.isSuccess()) {
            return response;
        }
        List<MobileBrandManagement> list = response.getData();
        if (list == null || CollectionUtils.isEmpty(list)) {
            return Response.error("上传文件中无数据需要处理");
        }

        mobileBrandService.addBatch(list);
        return Response.success("批量添加成功");
    }

}

Service 层处理 Excel 文件,取出数据做相应的业务处理。

到此,Vue 上传文件到后端完成,效果如下:


image.png
上一篇下一篇

猜你喜欢

热点阅读