通过JSF动作方法下载Excel文件会导致前面添加一些奇怪的字符并附加完整的JSP页面

时间:2013-04-17 12:49:24

标签: excel jsf download

我正在使用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。

我尝试使用纯文本文件,然后我可以打开它。

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

1 个答案:

答案 0 :(得分:1)

  

上面有一些奇怪的字符

您需要事先reset the response

response.reset();

另一个可能的原因是正在保存的文件本身已损坏。例如。使用Writer代替OutputStream保存。


  

以下是JSP

的完整代码

您需要tell JSF that you've already completed the response yourself,以便在调用操作方法后它不会执行默认导航和渲染响应作业。

context.responseComplete();

另见: