如何在 Spring MVC 中将字节数组转换为 ZipOutputStream?

Posted

技术标签:

【中文标题】如何在 Spring MVC 中将字节数组转换为 ZipOutputStream?【英文标题】:How to convert byte array to ZipOutputStream in spring MVC? 【发布时间】: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();
    

【问题讨论】:

查看此链接:***.com/questions/8367126/… 你已经有一个拉链。直接将byte[]写入OutputStream。不需要拉链的东西。 @M.Deinum,谢谢你成功了。我以前没有使用过这个文件程序。 【参考方案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 可以直接通过输出流发送。

以上是关于如何在 Spring MVC 中将字节数组转换为 ZipOutputStream?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Spring MVC (JPA) 中将实体对象列表转换为页面对象?

如何在php中将字节数组转换为整数?

如何在c ++中将int数组转换为字节数组[重复]

如何在 iPhone 中将 NSData 转换为字节数组?

如何在C ++中将字节数组中的整数转换为数字

如何在c ++中将数组字节转换为字符串?