java - 如何在 Spring MVC 中将字节数组转换为 ZipOutputStream?
问题描述
试图读取作为字节数组存储在数据库中的 zip 文件。
.zip 正在使用以下代码下载,但 zip 中包含的文件大小为零。没有数据。
我已经经历了很多答案,但不确定以下代码有什么问题。
请协助。
@RequestMapping(value = ApplicationConstants.ServiceURLS.TRANSLATIONS + "/{resourceId}/attachments", produces = "application/zip")
public void attachments(HttpServletResponse response, @PathVariable("resourceId") Long resourceId) throws IOException {
TtTranslationCollection tr = translationManagementDAO.getTranslationCollection(resourceId);
byte[] fileData = tr.getFile();
// setting headers
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Content-Disposition", "attachment; filename=\"attachements.zip\"");
ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(fileData));
ZipEntry ent = null;
while ((ent = zipStream.getNextEntry()) != null) {
zipOutputStream.putNextEntry(ent);
}
zipStream.close();
zipOutputStream.close();
}
解决方案
您还必须将 zip 文件的字节数据(内容)复制到输出中......
这应该有效(未经测试):
while ((ent = zipStream.getNextEntry()) != null) {
zipOutputStream.putNextEntry(ent);
// copy byte stream
org.apache.commons.io.IOUtils.copy(zis.getInputStream(ent), zipOutputStream);
}
顺便说一句:为什么你不只是简单地转发原始 zip 字节内容?
try (InputStream is = new ByteArrayInputStream(fileData));) {
IOUtils.copy(is, response.getOutputStream());
}
甚至更好(感谢@M. Deinum 的评论)
IOUtils.copy(fileData, response.getOutputStream());
推荐阅读
- java - 如何在使用并行 TestNG 方法时同步 Java 中的块/方法?
- sql - SQL 按自定义顺序排序
- python - 在 Python 中将具有行/列索引的数据转换为表
- python - Python - 将数据转移到不同的行
- react-native - 卸载并移动屏幕后在 Audio.Sound() 上调用的方法
- r - 如何将 diff() 与 group_by() 结合使用
- jekyll - 使用分页时如何按修改日期对帖子进行排序?
- sql - SQL:根据最近的日期选择一个字段中的值是唯一的记录
- c# - StackLayout 中的 ChartView 截断图表
- angular - 您好,我在发出 http 删除请求时收到以下错误