SpringBoot中将图片和Excel表格打包成压缩文件供前端下载

本文主要是介绍SpringBoot中将图片和Excel表格打包成压缩文件供前端下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、需求:

今天碰到了一个需求,就是将COS对象存储的图片和后端的数据库查询出来的用户的信息的excel表格一起打包成一个压缩包提供给前端下载。

二、分析:

作者的思路是这样的: 从COS的存储地址拿到对应图片的流(这个可以参考腾讯云的COS对象的下载 腾讯云COS操作文档) 再拿到一个此用户excel表格的流,将这些流转换成byte[] 数组,供压缩类进行打包成同一个文件时进行二次使用,也就是将流转换成字节数组,供二次使用,压缩类再由此字节数组转换成输入流,再由压缩类的输出流,将此输入流一个一个的刷新到前端。

三、环境搭建:

  1. 引入处理excel表格的依赖、hutool工具包、cos对象存储的依赖(这里我就不一一介绍如何配置对象存储了,具体的可以参考上诉的腾讯云文档)
<properties><poi.version>4.1.0</poi.version><poi-ooxml.version>4.1.0</poi-ooxml.version><cos_api.version>5.6.15</cos_api.version><hutool-all.version>5.1.0</hutool-all.version>
</properties><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>${poi.version}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>${poi-ooxml.version}</version></dependency><dependency><groupId>com.qcloud</groupId><artifactId>cos_api</artifactId><version>${cos_api.version}</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool-all.version}</version></dependency>

四、功能实现:

  1. 通过cosClinet获取输入流(这里作者是使用了多个不同地区的存储桶):
    /*** 根据path 到相应地区的存储桶 获取图片的下载输入流和图片的名字* @param path 数据库字段对应的图片url地址* @return*/public InputStream downLoadResourceFromBucket(String path){String[] split = path.split("\\.");String[] split2 = path.split("/");String bucketName = split[0].substring(8);String area = split[2];String key = "student-photo" + "/" +split2[split2.length - 1];GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);COSObject object = null;if(area.equals(tenXunUtil.getAreaSH())){object =  cosClientSH.getObject(getObjectRequest);}else if(area.equals(tenXunUtil.getAreaGZ())){object = cosClientGZ.getObject(getObjectRequest);}COSObjectInputStream objectInputStream = object.getObjectContent();return objectInputStream;}
  1. 将图片和excel表格进行生成相应的字节数组存放到Map<String,byte[]>结构中,k:表示将要使用的文件名。
    /*** 对资源进行处理,并且处理成字节数组* k:文件名  v:输入流转换成的字节数组.* @return*/public Map<String,byte[]> addByteArrayToInputStreamMap(User user){Map<String,byte[]> inputStreamMap = new ConcurrentHashMap<>();//获取图片流资源转换成字节数组if(!ObjectUtils.isEmpty(user.getRedHeadUrl())){InputStream inputStream = null;try {inputStream = myUtils.downLoadResourceFromBucket(user.getRedHeadUrl());String[] split = user.getRedHeadUrl().split("\\.");String redName = "red" + "." + split[split.length - 1];//上诉为直接通过Cos获取图片的输入流,如果小伙伴们想通过图片url直接获取输入流可以这么写://           URL url = new URL(user.getRedHeadUrl());//          HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();//         httpsURLConnection.connect();//       inputStream = httpsURLConnection.getInputStream();byte[] bytes = IOUtils.toByteArray(inputStream);inputStreamMap.put(redName,bytes);} catch (IOException e) {e.printStackTrace();} finally {if(inputStream != null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}if(!ObjectUtils.isEmpty(user.getBlueHeadUrl())){InputStream inputStream = null;try {inputStream = myUtils.downLoadResourceFromBucket(user.getBlueHeadUrl());String[] split = user.getBlueHeadUrl().split("\\.");String redName = "blue" + "." + split[split.length - 1];byte[] bytes = IOUtils.toByteArray(inputStream);inputStreamMap.put(redName,bytes);} catch (IOException e) {e.printStackTrace();} finally {if(inputStream != null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}if(!ObjectUtils.isEmpty(user.getWhiteHeadUrl())){InputStream inputStream = null;try {inputStream = myUtils.downLoadResourceFromBucket(user.getWhiteHeadUrl());String[] split = user.getWhiteHeadUrl().split("\\.");String redName = "white" + "." + split[split.length - 1];byte[] bytes = IOUtils.toByteArray(inputStream);inputStreamMap.put(redName,bytes);} catch (IOException e) {e.printStackTrace();} finally {if(inputStream != null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}if(!ObjectUtils.isEmpty(user.getFrontIdCardUrl())){InputStream inputStream = null;try {inputStream = myUtils.downLoadResourceFromBucket(user.getFrontIdCardUrl());String[] split = user.getFrontIdCardUrl().split("\\.");String redName = "frontIdCard" + "." + split[split.length - 1];byte[] bytes = IOUtils.toByteArray(inputStream);inputStreamMap.put(redName,bytes);} catch (IOException e) {e.printStackTrace();} finally {if(inputStream != null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}if(!ObjectUtils.isEmpty(user.getBackIdCardUrl())){InputStream inputStream = null;try {inputStream = myUtils.downLoadResourceFromBucket(user.getBackIdCardUrl());String[] split = user.getBackIdCardUrl().split("\\.");String redName = "backIdCard" + "." + split[split.length - 1];byte[] bytes = IOUtils.toByteArray(inputStream);inputStreamMap.put(redName,bytes);} catch (IOException e) {e.printStackTrace();} finally {if(inputStream != null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}if(!ObjectUtils.isEmpty(user.getGraduationUrl())){InputStream inputStream = null;try {inputStream = myUtils.downLoadResourceFromBucket(user.getGraduationUrl());String[] split = user.getGraduationUrl().split("\\.");String redName = "graduation" + "." + split[split.length - 1];byte[] bytes = IOUtils.toByteArray(inputStream);inputStreamMap.put(redName,bytes);} catch (IOException e) {e.printStackTrace();} finally {if(inputStream != null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}}HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet sheet = workbook.createSheet("学员信息表");String[] headerLines =  {"姓名","身份证号","籍贯","报考省份","人事网账号","人事网密码"};HSSFRow headerRow = sheet.createRow(0);for (int j = 0; j < headerLines.length ; j++) {headerRow.createCell(j).setCellValue(new HSSFRichTextString(headerLines[j]));}HSSFRow row = sheet.createRow(1);row.createCell(0).setCellValue(user.getTrueName());row.createCell(1).setCellValue(user.getIdCard());row.createCell(2).setCellValue(user.getFromProvince());row.createCell(3).setCellValue(user.getExamProvince());row.createCell(4).setCellValue(user.getPeopleAccount());row.createCell(5).setCellValue(user.getPeoplePassword());byte[] excelByte = workbook.getBytes();String excelFileName = user.getTrueName() + ".xls";inputStreamMap.put(excelFileName,excelByte);return inputStreamMap;}
  1. 将这个Map<String,byte[]> 交给压缩成压缩包的方法区进行将多个文件压缩成压缩包,并且进行调用:

压缩方法:

   /*** 将每个文件的的字节数组添加到压缩包中* @param inputStreamMap* @param zipOutputStream*/public void zipFile(Map<String,byte[]> inputStreamMap, ZipOutputStream zipOutputStream){inputStreamMap.forEach((k,v) ->{String fileName = k;InputStream is = new ByteArrayInputStream(v);ZipEntry zipEntry = new ZipEntry(fileName);try {zipOutputStream.putNextEntry(zipEntry);//hutool工具包,直接将输入流刷新到输出流IoUtil.copy(is,zipOutputStream);} catch (IOException e) {e.printStackTrace();}finally {try {if(is != null){is.close();}} catch (IOException e) {e.printStackTrace();}}});}

调用的方法:
这里需要特别的提醒,**关流的时候一定要先关闭外层的流再关闭内层流,**不然的话压缩文件里面的文件会出现最后一个文件字节丢失,作者在这一步被坑了好久,内心是崩溃的!!!!。

    public void  findUserByIdCardToDown(HttpServletResponse response, String idCard) {User user = userMapper.findOneStudentByIdCard(idCard);if(!ObjectUtils.isEmpty(user)){response.setContentType(" application/x-msdownload; charset=UTF-8");Map<String, byte[]> inputStreamMap = addByteArrayToInputStreamMap(user);//为了避免下载文件名为中文时出现乱码 谷歌浏览器进行URL编码,火狐和IE进行Base4编码String  fileName = URLEncoder.encode(user.getTrueName() + ".zip",Charsets.UTF_8);ServletOutputStream os = null;ZipOutputStream  zipOutputStream = null;try {response.setHeader("Content-disposition", "attachment; filename=" + fileName);response.flushBuffer();os = response.getOutputStream();//生成压缩输出流zipOutputStream = new ZipOutputStream (os);zipFile(inputStreamMap,zipOutputStream);} catch (IOException e) {e.printStackTrace();}finally {//一定要先关闭外层流 坑位!!!!if(zipOutputStream != null){try {zipOutputStream.close();} catch (IOException e) {e.printStackTrace();}}if(os != null){try {os.close();} catch (IOException e) {e.printStackTrace();}}}}else{response.setContentType("text/html; charset=UTF-8");try {response.getWriter().write("暂无此身份证号的学员");} catch (IOException e) {e.printStackTrace();}}}
  1. 最后加上Controller层完成接口,再加上前端的一点小小的实现,最终的结果如下图:

在这里插入图片描述
在这里插入图片描述

五、总结

其实整个业务很常见,也不是很难,重要的是要理解IO流,以及流的传输。而且关闭流的时候一定要要先关闭外层的流,再关闭内层的流。

这篇关于SpringBoot中将图片和Excel表格打包成压缩文件供前端下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1065425

相关文章

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字

java中long的一些常见用法

《java中long的一些常见用法》在Java中,long是一种基本数据类型,用于表示长整型数值,接下来通过本文给大家介绍java中long的一些常见用法,感兴趣的朋友一起看看吧... 在Java中,long是一种基本数据类型,用于表示长整型数值。它的取值范围比int更大,从-922337203685477

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

SpringBoot服务获取Pod当前IP的两种方案

《SpringBoot服务获取Pod当前IP的两种方案》在Kubernetes集群中,SpringBoot服务获取Pod当前IP的方案主要有两种,通过环境变量注入或通过Java代码动态获取网络接口IP... 目录方案一:通过 Kubernetes Downward API 注入环境变量原理步骤方案二:通过