0

我有一个文件夹,我正在尝试压缩它,而不是在按钮单击事件上,它应该下载到用户的机器上。我能够正确生成 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";
}
4

1 回答 1

1

请参阅JSF 2.0 RenderResponse 和 ResponseComplete

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

于 2013-08-26T07:17:30.893 回答