Rachit M Garg
Rachit M Garg

Reputation: 281

Unable to download the created zipped file correctly from server

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.

How is this caused and how can I solve it? Here's the 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";
}

Upvotes: 0

Views: 831

Answers (1)

noone
noone

Reputation: 19776

See JSF 2.0 RenderResponse and ResponseComplete

The problem is that you do not call FacesContext#responseComplete(). That's why JSF will still render the view after you attached the download and append that to the response. This will cause the zipfile to be broken.

Upvotes: 1

Related Questions