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

3

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

字节数组来自于一个webservice,该webservice原本是一个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(); 
1个回答

0
我这里假设你想将一个字节数组保存到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) 现在要将它取回并下载,您需要一个控制器:

@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();
}

我已经编辑了我手头的代码,所以在它完全适合你之前,你需要做一些更改。如果这是你想要的,请告诉我。如果不是,我会删除我的回答。祝你使用愉快。


谢谢您的回复。输入不是一个zip文件。我得到了一个zip文件的字节数组。现在我需要将其转换为zip文件,并在请求时使其下载。 - user2390827
是的... 我给你的代码假定输入是一个字节数组...将文件保存为ZIP格式在磁盘上,方便随时下载。 - We are Borg
太棒了,它起作用了,非常感谢。但是在你的代码中有一个疑问,你正在输出到一个文件中,我能否在不将其存储到硬盘上的情况下下载这个文件? - user2390827
为什么不给文件随机命名,并在下载完成后删除该文件。另外,请将答案标记为已接受并点赞,如果它起作用的话。 - We are Borg
我能够这样做,但我需要在进行操作时即时处理,而不是将其存储在硬盘中,只需显示下载选项。感谢您的帮助。 - user2390827

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接