使用JSF 2.2下载文件返回content-length = 0

时间:2014-05-26 08:42:26

标签: eclipse jsf io xhtml glassfish-4

我正在尝试从JSF页面下载文件,但在检查浏览器中的content-length时,我发现它为0。

这是我在托管Bean中的方法:

  public void downloadFile() throws IOException {
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        File file = new File("C:\\data\\contacts.doc");
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=contacts.doc");  
        response.setContentLength((int) file.length());  
        response.setContentType("application/octet-stream");
        OutputStream out = response.getOutputStream();  
        try {  
            FileInputStream input = new FileInputStream(file); 
            byte[] buffer =new byte[2048];
           int offset = 0; 
            int byteRead =0;
          while ((offset= input.read(buffer))!= -1 ) {  

               offset += byteRead ;
                out.write(buffer,0,offset);  

           }  
           out.flush();
           out.close();
           input.close();
            FacesContext.getCurrentInstance().getResponseComplete();  
        } catch (IOException err) {  
            err.printStackTrace();  
        } finally {  
            try {  
                if (out != null) {  
                    out.close();  
                }  
            } catch (IOException err) {  
                err.printStackTrace();  
            }  
        }

这是xhtml页面:

<h:form>
   <h:commandButton value="Download" action="#{helloBean.downloadFile}" />
</h:form>

我正在使用Eclispe + Glassfish 4。

1 个答案:

答案 0 :(得分:0)

我是扩展问题,我把.docx代替.doc(.doc不再存在)