gpt4 book ai didi

java - 如何将字节数组转换为 ZIP 文件并使用 Java 下载?

转载 作者:行者123 更新时间:2023-12-05 07:53:06 25 4
gpt4 key购买 nike

我需要编写代码将字节数组转换为 ZIP 文件并使其在 Spring MVC 中下载。

字节数组来自最初是 ZIP 文件的网络服务。 ZIP 文件有一个文件夹,该文件夹包含 2 个文件。我编写了以下代码以将字节数组转换为 ZipInputStream。但我无法转换成 ZIP 文件。请帮助我。

这是我的代码。

ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry entry = null;
while ((entry = zipStream.getNextEntry()) != null) {

String entryName = entry.getName();

FileOutputStream out = new FileOutputStream(entryName);

byte[] byteBuff = new byte[4096];
int bytesRead = 0;
while ((bytesRead = zipStream.read(byteBuff)) != -1)
{
out.write(byteBuff, 0, bytesRead);
}

out.close();
zipStream.closeEntry();
}
zipStream.close();

最佳答案

我假设您要将字节数组写入 ZIP 文件。由于发送的数据也是ZIP文件,保存的也是ZIP文件,应该没有问题。

需要两个步骤:将其保存到磁盘并返回文件。

1) 存盘部分:

File file = new File(/path/to/directory/save.zip);
if (file.exists() && file.isDirectory()) {
try {
OutputStream outputStream = new FileOutputStream(new File(/path/to/directory/save.zip));
outputStream.write(bytes);
outputStream.close();
} catch (IOException ignored) {

}
} else {
// create directory and call same code
}
}

2) 现在要取回并下载它,您需要一个 Controller :

@RequestMapping(value = "/download/attachment/", method = RequestMethod.GET)
public void getAttachmentFromDatabase(HttpServletResponse response) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFileName() + "\"");
response.setContentLength(file.length);

FileCopyUtils.copy(file as byte-array, response.getOutputStream());
response.flushBuffer();
}

我已经编辑了我的代码,因此您必须进行一些更改才能使它 100% 适合您。让我知道这是否是您要找的。如果没有,我会删除我的答案。享受吧。

关于java - 如何将字节数组转换为 ZIP 文件并使用 Java 下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33129023/

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