JSF下载文件返回index.jsf

时间:2013-08-29 19:00:58

标签: java jsf-2 richfaces jboss7.x

我试图通过JSF实现相同的下载文件,如这些帖子中所述: JSF2 download file returns xhtml page source How to provide a file download from a JSF backing bean? http://bharatonjava.wordpress.com/2013/02/01/downloading-file-in-jsf-2/ http://prabinhada.blogspot.com/2012/06/how-to-download-file-using-jsf.html

我的问题是我实际上可以下载该文件,但它的名称是错误的(在任何浏览器上)。 这是我在下载方法中编组的XML文件,但浏览器总是收到一个文件index.jsf(但mime类型设置为text / xml,文件大小正确)

它运行于:

  • Mojarra 2.1.7
  • Richfaces 4.3.3.Final
  • jboss-7.1.1.Final

如果您发现任何问题,请参阅下文

    public void exportEDL() throws Exception {
    String name = this.file.getName();
    FacesContext facesContext = FacesContext.getCurrentInstance();      

    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    BufferedOutputStream output = null;
    StringWriter sw = null;
    try {

        ...
        sw = new StringWriter();
        // edl is the jaxb i want to return as xml file
        marshaller.marshal(this.edl, sw);

        // Init servlet response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);  
        response.setContentType("text/xml");
        response.setContentLength( sw.getBuffer().length() );
        response.setHeader("Content-Disposition", "attachment;filename\"" + name + "\"");
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
        output.write(sw.toString().getBytes("UTF-8"));

        // Finalize task.
        sw.flush();
        output.flush();
    } catch ( Exception e ) {    
        FacesMessage msg = new FacesMessage( FacesMessage.SEVERITY_ERROR, null, e.getMessage() );  
        facesContext.addMessage("Error", msg); 
        return;
    } finally {
        // Gently close streams.
        IOUtil.close(sw);
        IOUtil.close(output);
        clearUploadData();
    }

    // Inform JSF that it doesn't need to handle response.
    facesContext.responseComplete();
   // facesContext.renderResponse();
   // facesContext.release();
}

我尝试使用除XML编组之外的其他内容而没有更好的结果。 你们有没有设法下载一个名称+扩展名正确的文件?

视图中是commandButton:

<h:commandButton action="#{fileUploadBean.exportEDL()}"

谢谢!

1 个答案:

答案 0 :(得分:2)

你似乎错过了=,我认为这是对的:

response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");

或只是

response.setHeader("Content-Disposition", "attachment;filename=" + name);