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

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件