user5620472 user5620472 - 24 days ago 5
Java Question

How can I download zip file from controller on client side? Spring boot

I have

file.zip
in DB like
BLOB
. I want create method in Spring controller for download this file on client side.

@RequestMapping(value = "/downloadResolution/{resolutionId}", method = RequestMethod.GET)
public void downloadResolution(@PathVariable("resolutionId") Long resolutionId, HttpServletResponse response) {
Resolution resolution = resolutionService.findOne(resolutionId);
ResolutionArchive resolutionArchive = resolution.getResolutionArchive();
if (resolutionArchive == null) return;
byte[] archive = resolutionArchive.getArchive();
//this byte[] archive - my zip file from db
}


How can I change this methot In order to download this on client side?

User press download button. Methos get data from DB in byte[] and user can download it.

EDIT

I tried solution of @pleft and it work. and I knew - I use ajax for call method

function downloadResolution(resulutionId) {
$.ajax({
type: 'GET',
dataType: "json",
url: '/downloadResolution/' + resulutionId,
success: function (data) {
},
error: function (xhr, str) {
}
});
}


How realize this if I use ajax?

Answer

You can use the OutputStream of your HttpServletResponse to write your archive bytes there.

e.g.

response.setHeader("Content-Disposition", "attachment; filename=file.zip");
response.setHeader("Content-Type", "application/zip");
response.getOutputStream().write(archive);

EDIT

Sample download

@RequestMapping(value = "/downloadResolution/{resolutionId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadResolution(@PathVariable("resolutionId") Long resolutionId, HttpServletResponse response) throws IOException {
    String test = "new string test bytes";
    response.setHeader("Content-Disposition", "attachment; filename=file.txt");
    response.getOutputStream().write(test.getBytes());
}
Comments