Element UI + Easypoi + spring boot 完成文件上传和下载

一 前端

1 文件上传下载


下载


  点击上传

2 数据部分

data () {
  return {
    fileList: [], // 上传文件列表
    url: '', // 上传 url
    downUrl: '' // 下载 url
  }
},

3 数据初始化

activated () {
  // 上传地址初始化
  this.url = this.$http.BASE_URL + `/bus/marketCapacitydatadetail/upload?token=${this.$cookie.get('token')}`
  // 下载地址初始化
  this.downUrl = this.$http.BASE_URL + `/bus/marketCapacitydatadetail/down?token=${this.$cookie.get('token')}`
  // 重新拉取数据
  this.getDataList()
},

4 JS 逻辑代码

// 上传之前判断文件类型
beforeUploadHandle (file) {
  if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
    this.$message.error('只支持 xlsx、xls格式的文件!')
    return false
  }
},
// 上传成功的简单处理
successHandle (response, file, fileList) {
  this.getDataList()
  this.fileList = fileList
},
// 下载数据到文件
download () {
  window.location.href = this.downUrl
}

二 后端

1 pom



    4.0.0




    cn.afterturn
    easypoi-base
    ${easypoi.version}


    cn.afterturn
    easypoi-web
    ${easypoi.version}


    cn.afterturn
    easypoi-annotation
    ${easypoi.version}

2 上传和下载的核心代码

/**
* 上传文件
*
* @param file 上传文件
* @return RestResponse
*/
@RequestMapping("/upload")
public RestResponse upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
    JSONObject json = new JSONObject();
    if (file == null) {
        return null;
    }
    ImportParams params = new ImportParams();
    params.setTitleRows(0);
    params.setHeadRows(1);
    List list = null;

    try {
        list = ExcelImportUtil.importExcel(file.getInputStream(), CompetitiveProductDataEntity.class, params);
        for (int i = 0; i < list.size(); i++) {
            competitiveProductDataService.add(list.get(i));
        }
        return RestResponse.success();
    } catch (NoSuchElementException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return RestResponse.error();
}

/**
* 功能描述:下载文件
*
* @param request  请求
* @param response 响应
* @author chengqiuming
* @date 2023/3/23
*/
@GetMapping("/down")
public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // 告诉浏览器用什么软件可以打开此文件
    response.setHeader("content-Type", "application/vnd.ms-excel");
    // 下载文件的默认名称
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("文件名称", "UTF-8") + ".xls");
    // 编码
    response.setCharacterEncoding("UTF-8");
    List list = competitiveProductDataService.queryAll(new HashMap<>());
    Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), CompetitiveProductDataEntity.class, list);
    workbook.write(response.getOutputStream());
}

你可能感兴趣的:(Spring,Boot,java,Vue,spring,boot,javascript,element,UI,文件上传和下载,EasyPoi)