首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将字节数组转换为ZIP文件并使用Java下载?

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

Stack Overflow用户
提问于 2015-10-14 15:06:45
回答 1查看 7.9K关注 0票数 3

我需要编写一个代码来将字节数组转换为ZIP文件,并将其下载到Spring中。

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

这是我的密码。

代码语言:javascript
复制
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(); 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-14 15:28:21

我在这里假设您想要将字节数组写入ZIP文件。由于发送的数据也是一个ZIP文件,而要保存的数据也是ZIP文件,所以应该不会有问题。

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

1)磁盘部分保存:

代码语言:javascript
复制
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)现在要把它拿回来并下载,您需要一个控制器:

代码语言:javascript
复制
@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%适合您之前进行一些更改。如果这是你要找的东西请告诉我。否则,我会删除我的答覆。好好享受吧。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33129023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档