React获取Java文件 React获取Java后台文件流并下载Excel文件流程解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React获取Java文件 React获取Java后台文件流并下载Excel文件流程解析

不少于4个字节   2021-04-22 我要评论

记录使用blob对象接收java后台文件流并下载为xlsx格式的详细过程,关键部分代码如下。

首先在java后台中设置response中的参数:

public void exportExcel(HttpServletResponse response, String fileName, String sheetName,
            List<String> titleRow, List<List<String>> dataRows) {
  OutputStream out = null;
  try {
    // 设置浏览器解析文件的mime类型,如果js中已设置,这里可以不设置
    // response.setContentType("application/vnd.ms-excel;charset=gbk");
    // 设置此项,在IE浏览器中下载Excel文件时可弹窗展示文件下载
    response.setHeader("Content-Disposition", 
              "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
   	// 允许浏览器访问header中的FileName
   	response.setHeader("Access-Control-Expose-Headers", "FileName");
    // 设置FileName,转码防止中文乱码
    response.setHeader("FileName", URLEncoder.encode(fileName, "UTF-8"));
    
    out = response.getOutputStream();
    ExcelUtils.createExcelStream(out, sheetName, titleRow, dataRows);
    out.close();
  } catch (Exception e) {
    if (Objects.nonNull(out)) {
      try {
        out.close();
      } catch (IOException e1) {
        log.error("导出失败", e);
      }
    }
    throw Exceptions.fail(ErrorMessage.errorMessage("500", "导出失败"));
  }
}

此时在浏览器的调试面板中可以看到导出接口的response header参数如下:

access-control-allow-credentials: true
access-control-allow-methods: GET,POST,PUT,DELETE,OPTIONS
access-control-allow-origin: http://local.dasouche-inc.net:8081
access-control-expose-headers: FileName
connection: close
content-type: application/vnd.ms-excel;charset=gbk
date: Sun, 29 Mar 2020 10:59:54 GMT
filename: %E4%B8%BB%E6%92%AD%E5%88%97%E8%A1%A8166296222340726.xlsx

接下来我们在前端代码中获取文件流:

handleExport = () => {
  axios.post(`下载文件的接口请求路径`, {}, {
    params: {
      参数名1: 参数值1,
      参数名2: 参数值2
    },
    // 设置responseType对象格式为blob
    responseType: "blob"
  }).then(res => {
	   // 创建下载的链接
    const url = window.URL.createObjectURL(new Blob([res.data],
		// 设置该文件的mime类型,这里对应的mime类型对应为.xlsx格式                          
      {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
    const link = document.createElement('a');
    link.href = url;
   	// 从header中获取服务端命名的文件名
   	const fileName = decodeURI(res.headers['filename']);
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
  });
};


至此就可以愉快地下载xlsx格式的文件啦~

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们