如何通过React实现下载Java后端提供的Excel文件流?
- 内容介绍
- 文章标签
- 相关推荐
本文共计527个文字,预计阅读时间需要3分钟。
使用Blob对象接收Java后端文件流并下载为xlsx格式的详细步骤如下:
1. 在Java后端设置Response参数:javapublic void exportExcel(HttpServletResponse response, String fileName, StreamingResponseBody body) {
2. 设置Response的MIME类型和内容长度:javaresponse.setContentType(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet);response.setHeader(Content-Disposition, attachment;filename= + fileName);response.setHeader(Content-Length, body.contentLength());
3. 将文件流写入Response输出流:javaOutputStream outputStream=response.getOutputStream();body.writeTo(outputStream);outputStream.flush();outputStream.close();
记录使用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: 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格式的文件啦~
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。
本文共计527个文字,预计阅读时间需要3分钟。
使用Blob对象接收Java后端文件流并下载为xlsx格式的详细步骤如下:
1. 在Java后端设置Response参数:javapublic void exportExcel(HttpServletResponse response, String fileName, StreamingResponseBody body) {
2. 设置Response的MIME类型和内容长度:javaresponse.setContentType(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet);response.setHeader(Content-Disposition, attachment;filename= + fileName);response.setHeader(Content-Length, body.contentLength());
3. 将文件流写入Response输出流:javaOutputStream outputStream=response.getOutputStream();body.writeTo(outputStream);outputStream.flush();outputStream.close();
记录使用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: 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格式的文件啦~
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

