无法从服务器正确下载创建的压缩文件

时间:2013-08-26 06:44:30

标签: jsf zip

我有一个文件夹,我正在尝试压缩它,而不是按钮点击事件,它应该在用户的机器上下载。我能够正确生成zip文件。我已经编写了代码来下载它,但是从服务器上下载到用户的机器之后。它显示无法打开zip文件,因为它无效。

这是如何引起的,我该如何解决?这是执行下载功能的代码。

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";
}

1 个答案:

答案 0 :(得分:1)

请参阅JSF 2.0 RenderResponse and ResponseComplete

问题是你没有调用FacesContext #responseComplete()。这就是为什么JSF在您附加下载并将其附加到响应后仍将呈现视图的原因。这将导致zip文件被破坏。