Spring Rest - Create Zip File and Send It to the Client

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



Leave a reply



Submit