问题
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