Reputation: 722
I don't understand why this is so hard and everybody has it's own implementation...
So in my server, I generate a .zip
file which I want the user to be able to download upon click.
So I set up the request, which the server successfully receives and now, i'm struggling with writing the byte array to the output.
Here's my code for the response:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Downloading clusters.zip");
/* Generate the directory on the server, then zip it. */
clustersToFiles();
zipClusters();
/* Now the zip is saved on zipFullPath */
System.out.println("Done generating the .zip");
String parent_dir = System.getProperty("catalina.base");
String filename = "clusters.zip";
String zipFullPath = parent_dir + "/" + filename;
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
OutputStream out = response.getOutputStream();
FileInputStream fis = new FileInputStream(zipFullPath);
int bytes;
while ((bytes = fis.read()) != -1) {
System.out.println(bytes);
out.write(bytes);
}
fis.close();
response.flushBuffer();
System.out.println(".zip file downloaded at client successfully");
}
Upvotes: 3
Views: 6995
Reputation: 17534
The fact that the downloaded file is a ZIP isn't relevant (except for the content type), you just want to download a binary file.
PrintWriter
isn't good at that, this writer is used to write text output, and the write(int)
method you are using :
Writes a single character.
Just use a low level plain OutputStream
, its write(int)
method :
Writes the specified byte to this output stream.
So just go :
OutputStream out = response.getOutputStream();
You may find some more ways of doing it in this question : Implementing a simple file download servlet
Upvotes: 4