Jsf文件下载不起作用

标签 jsf jakarta-ee jsf-2 icefaces

当我单击 h:commandButton 时,它会执行 myBean.dowanlod() 方法,但不会下载任何文件。 这是我在支持 bean 中的方法。没有异常(exception)。光标变忙,似乎在等待响应。这种操作是否有额外的配置,或者这段代码有什么问题吗?

<h:commandButton value="download" action="#{myBean.download()}" /> 

@ManagedBean
@SessionScoped    
public class MyBean implements Serializable{
   //....

   public String download{

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();

    String fileName = "test.txt";
    String filePath = "D:\\test.txt"; //externalContext.getRealPath("") + File.separator + fileName;
    File file = new File(filePath);

    externalContext.setResponseHeader("Content-Type", "text/plain");
    externalContext.setResponseHeader("Content-Length", String.valueOf(file.length()));
    externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");


    InputStream input = null;
    OutputStream output = null;

    try {
        input = new FileInputStream(file);
        output = externalContext.getResponseOutputStream();
        IOUtils.copy(input, output);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
    }

    facesContext.responseComplete();
    return null;
  }

  //...
}

最佳答案

ICEfaces 有一个奇怪的“feature”,它隐式转换所有标准 JSF <h:commandButton>到支持 ajax 的命令按钮。但是,无法使用 ajax 下载文件。您需要明确将其关闭。您可以通过嵌套 <f:ajax disabled="true"> 在每个按钮的基础上执行此操作.

<h:commandButton value="download" action="#{myBean.download()}" />
    <f:ajax disabled="true"/>
</h:commandButton>

另见:

关于Jsf文件下载不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15131582/

相关文章:

html - 将 HTML 转换为 JSF

java - @RequiredStringValidator 使用表达式

java - Jersey 客户端 - 如何通过 POST 请求以表单形式发送列表

jakarta-ee - WFLYEJB0043 : A previous execution of timer [timer] is still in progress, 在 [时间] 跳过这个重叠的计划执行

jsf - Faces-redirect = true在JSF中

jakarta-ee - JSF2 搜索框

java - JSF 按时间间隔从应用程序 bean 轮询数据库

java - JSF 自定义 validator : h:message is not being rendered

jsf-2 - JSF 中未捕获的异常处理

java - 是否可以在jsf上使用xml-db作为数据库