我正在使用JSF,并且在其中一个托管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的整个代码。我甚至尝试过application / octet-stream for contenttype。
我尝试使用纯文本文件,然后我可以打开它。
请帮助我解决这个问题,提前致谢。
答案 0 :(得分:1)
上面有一些奇怪的字符
您需要事先reset the response。
response.reset();
另一个可能的原因是正在保存的文件本身已损坏。例如。使用Writer
代替OutputStream
保存。
以下是JSP
的完整代码
您需要tell JSF that you've already completed the response yourself,以便在调用操作方法后它不会执行默认导航和渲染响应作业。
context.responseComplete();