Jsf 无法从服务器正确下载创建的压缩文件
我有一个文件夹,我正试图压缩它,而不是在一个按钮点击事件,它应该下载到用户的机器上。我能够正确生成zip文件。我已经编写了代码来下载它,但是在它从服务器下载到用户机器之后。它显示无法打开zip文件,因为该文件无效 这是如何造成的,我如何解决?下面是执行下载功能的代码Jsf 无法从服务器正确下载创建的压缩文件,jsf,zip,Jsf,Zip,我有一个文件夹,我正试图压缩它,而不是在一个按钮点击事件,它应该下载到用户的机器上。我能够正确生成zip文件。我已经编写了代码来下载它,但是在它从服务器下载到用户机器之后。它显示无法打开zip文件,因为该文件无效 这是如何造成的,我如何解决?下面是执行下载功能的代码 public String getAsZip() { try { FacesContext ctx = FacesContext.getCu
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";
}
看
问题是您没有调用FacesContext#responseComplete()。这就是为什么JSF在您附加下载并将其附加到响应之后仍然呈现视图。这将导致拉链破裂