我正在使用 Primefaces 文件下载。当我第一次启动应用程序时,文件已下载,但每次我按下下载按钮时,都会出现此错误:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
我的 xhtml 代码:
<p:commandButton value="Download" ajax="true">
<p:fileDownload value="#{fileDownloadController.file}" />
</p:commandButton>
我的java代码:
private StreamedContent file;
public FileDownloadController() {
InputStream stream = null;
try {
stream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/Enastr1.txt");
file = new DefaultStreamedContent(stream, "txt", "Downloaded_Enastr1");
} catch (Exception ex) {
Logger.getLogger(FileDownloadController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
public StreamedContent getFile() {
return file;
}
public void setFile(StreamedContent file) {
this.file = file;
}
最佳答案
您是在 bean 的构造函数中创建流,而不是在与 <p:commandButton>
关联的操作方法中创建流.症状表明 bean 放置在比请求范围更广的范围内。构造函数仅在 bean 构造时调用,而不是在每个 HTTP 请求时调用。如果将 bean 放入请求范围内,则在每个 HTTP 请求上调用构造函数。
你有两个选择:
将 bean 放入请求范围内。
改为在操作方法中创建流并将其绑定(bind)到
<p:commandButton action>
.
关于java - Primefaces fileDownload - 已经为此响应调用了 getOutputStream(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7755493/