Spring Boot中字节数组转Zip文件为空问题求助
解决字节数组转Zip文件为空的问题
你的代码核心错误在于:你把解码后的Excel字节数组当成了Zip格式的输入流来读取,但实际上这个字节数组是普通Excel文件的内容,并非Zip包,所以ZipInputStream根本读不到任何有效数据,z.read(excel)直接返回-1,循环不执行,最终生成空Zip。
修正后的代码
正确做法是直接用ZipOutputStream创建Zip条目,将Excel字节数组写入该条目:
String resultBase64 = reportApplicationService.fetchReportExcel(...); if (resultBase64 != null) { byte[] excel = base64.decode(resultBase64); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (ZipOutputStream zip = new ZipOutputStream(outputStream)) { // 创建Zip内的文件条目,自定义文件名 ZipEntry excelEntry = new ZipEntry("report.xlsx"); zip.putNextEntry(excelEntry); // 将Excel字节数组写入Zip条目 zip.write(excel); zip.closeEntry(); zip.finish(); } // 配置响应并输出Zip文件 response.setHeader("Content-Disposition", "attachment; filename=name.zip"); response.setContentType("application/zip"); response.setContentLength(outputStream.size()); StreamUtils.copy(new ByteArrayInputStream(outputStream.toByteArray()), response.getOutputStream()); response.getOutputStream().flush(); }
关键修正点
- 移除了无效的
ZipInputStream读取逻辑,我们的需求是创建Zip而非解析Zip。 - 通过
ZipOutputStream.putNextEntry()定义Zip包内的文件结构,指定Excel在Zip中的显示名称。 - 直接将解码后的Excel字节数组写入Zip流,确保数据被正确打包。
- 使用try-with-resources语法自动管理流资源,避免泄漏。
内容的提问来源于stack exchange,提问作者mehnet ali
相关产品推荐
相关产品推荐

