本文主要是介绍SpringBoot中将图片和Excel表格打包成压缩文件供前端下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、需求:
今天碰到了一个需求,就是将COS对象存储的图片和后端的数据库查询出来的用户的信息的excel表格一起打包成一个压缩包提供给前端下载。
二、分析:
作者的思路是这样的: 从COS的存储地址拿到对应图片的流(这个可以参考腾讯云的COS对象的下载 腾讯云COS操作文档) 再拿到一个此用户excel表格的流,将这些流转换成byte[] 数组,供压缩类进行打包成同一个文件时进行二次使用,也就是将流转换成字节数组,供二次使用,压缩类再由此字节数组转换成输入流,再由压缩类的输出流,将此输入流一个一个的刷新到前端。
三、环境搭建:
- 引入处理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>
四、功能实现:
- 通过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;}
- 将图片和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;}
- 将这个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();}}}
- 最后加上Controller层完成接口,再加上前端的一点小小的实现,最终的结果如下图:
五、总结
其实整个业务很常见,也不是很难,重要的是要理解IO流,以及流的传输。而且关闭流的时候一定要要先关闭外层的流,再关闭内层的流。
这篇关于SpringBoot中将图片和Excel表格打包成压缩文件供前端下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!