通过JSF操作方法下载Excel文件会导致一些奇怪的字符被前置,并且完整的JSP页面被追加

我正在使用JSF和在一个托pipe的bean(视图范围)我有一个方法为:

public String viewReport() { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition","attachment;filename=book1.xls"); try { File file = new File("C:\\soheb\\book1.xls"); FileInputStream fileIn = new FileInputStream(file); ServletOutputStream out = response.getOutputStream(); byte[] outputByte = new byte[4096]; //copy binary contect to output stream while(fileIn.read(outputByte, 0, 4096) != -1) { out.write(outputByte, 0, 4096); } fileIn.close(); out.flush(); out.close(); } catch(IOException e) { e.printStackTrace(); } return null; } 

正在检索的Excel是损坏的文件。 上面有一些奇怪的字符,下面是JSP的全部代码。 我什至尝试应用程序/八位字节stream的contenttype也。

我尝试了一个纯文本文件,我可以打开它。

请帮助我解决这个问题,提前致谢。

上面有一些奇怪的字符

您需要事先重置响应 。

 response.reset(); 

另一个可能的原因是,被保存的文件本身是损坏的。 例如保存使用Writer而不是OutputStream


下面是JSP的完整代码

您需要告诉JSF自己已经完成了响应,以便在调用操作方法后,不会执行其默认导航并呈现响应作业。

 context.responseComplete(); 

也可以看看:

  • 如何从JSF支持bean提供文件下载?