【问题标题】:How to convert byte array to ZipOutputStream in spring MVC?如何在 Spring MVC 中将字节数组转换为 ZipOutputStream?
【发布时间】:2019-06-19 11:36:11
【问题描述】:

试图读取以字节数组形式存储在数据库中的 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();
    }

【问题讨论】:

  • 你已经有一个拉链。直接将byte[]写入OutputStream。不需要拉链的东西。
  • @M.Deinum,谢谢你成功了。我以前没有使用过这个文件程序。

标签: java spring spring-mvc zipoutputstream zipinputstream


【解决方案1】:

您还必须将 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());

【讨论】:

  • 谢谢。是的,它的 zip 可以直接通过输出流发送。
猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多