首页 > 解决方案 > 如何在 Spring MVC 中将字节数组转换为 ZipOutputStream?

问题描述

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

标签: javaspringspring-mvczipoutputstreamzipinputstream

解决方案


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

推荐阅读