Sunday, 25 August 2013

Unable to download the created zipped file correctly from server

Unable to download the created zipped file correctly from server

What I am trying to do is as follows: I am having a folder, I am trying to
zip it and than on a button click event it should be downloaded on the
user's machine. I am able to generate the zip file correctly. I have
written the code to download it also but after it is getting downloaded to
the user's machine from the server. It shows unable to open zip file as it
is invalid.
Please help in this. I am sharing my code which performs the download
functionality.
public String getAsZip() {
try {
FacesContext ctx = FacesContext.getCurrentInstance();
ExternalContext etx = ctx.getExternalContext();
HttpServletResponse response = (HttpServletResponse) etx
.getResponse();
ServletOutputStream zipFileOutputStream = response
.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader(
"Content-Disposition",
"attachment; filename=" +
downloadLink.substring(downloadLink.lastIndexOf("\\") +
1,downloadLink.length()));
response.setHeader("Cache-Control", "no-cache");
File zipFile = new File(downloadLink);
FileInputStream stream = new FileInputStream(zipFile);
response.setContentLength(stream.available());
int length = 0;
byte[] bbuf = new byte[response.getBufferSize()];
BufferedInputStream in = new BufferedInputStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((length = in.read(bbuf)) > 0) {
baos.write(bbuf, 0, length);
}
zipFileOutputStream.write(baos.toByteArray());
zipFileOutputStream.flush();
zipFileOutputStream.close();
response.flushBuffer();
in.close();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return "successZip";
}

No comments:

Post a Comment