如何在springbootjava中压缩多个文件并返回streamingresponsebody对象

57hvy0tb  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(236)

这个问题已经存在

如何在springbootjava中压缩多个文件并返回streamingresponsebody对象
上个月关门了。
在我的应用程序中,我必须将xml文件压缩到某个位置,并使其可供下载。因此我使用下面的逻辑。我的方法返回streamingresponsebody对象。当我尝试下载时,zip文件已损坏。我做错了什么?我该怎么解决这个问题?

headerValue = String.format("attachment; filename=\"%s\"", "configs.zip");
                String mimeType = "application/zip";
                String headerKey = "Content-Disposition";
                response.setContentType(mimeType);
                response.setHeader(headerKey, headerValue);
                response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
StreamingResponseBody stream = out -> {
    final File directory = new File(tmp_file_path);
    final ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
    if(directory.exists() && directory.isDirectory()) {
        try {
            for (final File file : directory.listFiles()) {
                final InputStream inputStream=new FileInputStream(file);
                final ZipEntry zipEntry=new ZipEntry(file.getName());
                zipOut.putNextEntry(zipEntry);
                byte[] bytes=new byte[1024];
                int length;
                while ((length=inputStream.read(bytes)) >= 0) {
                    zipOut.write(bytes, 0, length);
                }
                inputStream.close();
            }
            zipOut.close();
        } catch (final IOException e) {
            log.error("Exception while reading and streaming data {} ", e);
        }
    }
};
return stream;

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题