尝试读取以字节数组形式存储在数据库中的 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 - 如何在 Spring MVC 中将字节数组转换为 ZipOutputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666785/