I am able to download a single file but how I can download a zip file which contain multiple files.
Below is the code to download a single file but I have multiples files to download. Any help would greatly appreciated as I am stuck on this for last 2 days.
@GET
@Path("/download/{fname}/{ext}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@PathParam("fname") String fileName,@PathParam("ext") String fileExt){
File file = new File("C:/temp/"+fileName+"."+fileExt);
ResponseBuilder rb = Response.ok(file);
rb.header("Content-Disposition", "attachment; filename=" + file.getName());
Response response = rb.build();
return response;
}
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.