How to download a zip file in Java
In our previous article, we showed how to download a file of any type from a servlet.
Now for zip files, things are a bit different, in this tutorial, we specifically show how to write a zip file to an HTTP response and download it to the browser.
1- Download a Zip file
In order to download a zip file in Java, we need to firstly set the content type of the HTTP response as “application/zip” and then write the zip file to the ServletOutputStream.
The following piece of code can be used whenever we need to download a zip file in Java:
1 2 3 4 5 6 7 8 | byte[] zip = // your zip file is defined here response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=output.zip"); ServletOutputStream sos = response.getOutputStream(); sos.write(zip); sos.flush(); |
it’s not complete code