您的位置:首页技术文章
文章详情页

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

【字号: 日期:2022-05-29 10:11:31浏览:50作者:猪猪

记录使用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: trueaccess-control-allow-methods: GET,POST,PUT,DELETE,OPTIONSaccess-control-allow-origin: http://local.dasouche-inc.net:8081access-control-expose-headers: FileNameconnection: closecontent-type: application/vnd.ms-excel;charset=gbkdate: Sun, 29 Mar 2020 10:59:54 GMTfilename: %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格式的文件啦~

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: excel
相关文章: