How to zip multiple files and return StreamingResponseBody object in spring boot java

十年热恋 提交于 2020-11-30 02:03:38

问题


In my application I have to zip XML files in a location, and make it available for download. Hence I'm using the below logic. My method returns StreamingResponseBody object. When I try to download, the zip file is corrupted. What am I doing wrong, and how do I fix this?

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;

来源:https://stackoverflow.com/questions/64908423/how-to-zip-multiple-files-and-return-streamingresponsebody-object-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!