gpt4 book ai didi

java - 多个文件存档的 ZIP 文件 servlet 响应已损坏

转载 作者:行者123 更新时间:2023-12-01 16:01:24 27 4
gpt4 key购买 nike

我正在尝试压缩文件包并通过 servlet 返回 ZIP。如果我只有一个文件,则效果很好,但当我尝试添加更多文件时,它们似乎只是被附加到第一个 ZipEntry 中,因此 zip 存档会损坏。

private void writeZipResponse(HttpServletResponse response,
List<File> bundle) {
try {
ByteArrayOutputStream bout=new ByteArrayOutputStream();
ZipOutputStream zout = new ZipOutputStream(bout);
ServletOutputStream out =response.getOutputStream();

for (File file : bundle) {
FileInputStream fi = new FileInputStream(file);
byte bytes[] = new byte[(int)file.length()];

// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=fi.read(bytes, offset, bytes.length-offset)) >= 0)
{ offset += numRead; }

// Ensure all the bytes have been read in
if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); }
fi.close();

ZipEntry zipEntry = new ZipEntry(file.getName());
//zipEntry.setCompressedSize(file.length());
zipEntry.setSize(offset);
CRC32 crc = new CRC32();
crc.update(bytes);
zipEntry.setCrc(crc.getValue());
zout.putNextEntry(zipEntry);
zout.write(bytes, 0, offset);
zout.closeEntry();
zout.finish();
fi.close();
}

zout.close();

response.setContentType("application/zip");
response.setHeader("Content-Disposition",
"attachment; filename=hivseqdb.zip;");
out.write(bout.toByteArray());
out.flush();
out.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

最佳答案

你需要移动zout.finish();循环外的线。

关于java - 多个文件存档的 ZIP 文件 servlet 响应已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3790588/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com