Spring boot rest service to download a zip file which contains multiple file
Use these Spring MVC provided abstractions to avoid loading of whole file in memory. org.springframework.core.io.Resource
& org.springframework.core.io.InputStreamSource
This way, your underlying implementation can change without changing controller interface & also your downloads would be streamed byte by byte.
See accepted answer here which is basically using org.springframework.core.io.FileSystemResource
to create a Resource
and there is a logic to create zip file on the fly too.
That above answer has return type as void
, while you should directly return a Resource
or ResponseEntity<Resource>
.
As demonstrated in this answer, loop around your actual files and put in zip stream. Have a look at produces
and content-type
headers.
Combine these two answers to get what you are trying to achieve.
How to return an encrypted zip file using Java Spring boot zip4j
The below code worked for me.
import net.lingala.zip4j.ZipFile;
@GetMapping(value = "/v1/downloadZipFileWithPassword")
ResponseEntity<StreamingResponseBody> downloadZipFileWithPassword(@RequestParam("password") String password) {
ZipFile zipFile = service.downloadZipFileWithPassword(password);
return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/zip"))
.header("Content-Disposition", "attachment; filename=\"Test.zip\"")
.body(outputStream -> {
try (OutputStream os = outputStream; InputStream inputStream = new FileInputStream(zipFile.getFile())) {
IOUtils.copy(inputStream, os);
}
});
}
Related Topics
Can Not Deserialize Instance of Java.Util.Arraylist Out of Start_Object Token
How to Disable Log4J Logging from Java Code
How to Check If a Json Key Exists
Jackson Jsonmappingexception: Can Not Deserialize Instance
Mock Objects Created Inside Method Under Test to Verify the Arguments Passed
How to Get Multiple Columns from Table Using Jpa
Wait Until All Threads Finish Their Work in Java
How to Multiply a and B With My Recursive Method
Springboot Data - No Property Registration Found
Httpclienterrorexception 400 Null Using Resttemplate in Microservices
How to Mock a Rest Template Exchange
How to Make a Multipart/Form-Data Post Request Using Java
Arraylist: How Does the Size Increase
Correct Way to Focus an Element in Selenium Webdriver Using Java
Java 8 Convert Utc Time to Edt/Est So That Date Remains the Same
How to Fix Expected Begin_Object But Was String in Retrofit