I’m using Primefaces fileDownload. When I first start the application the file is downloaded but then everytime I press the download button, this error appears:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
My xhtml code:
<p:commandButton value="Download" ajax="true">
<p:fileDownload value="#{fileDownloadController.file}" />
</p:commandButton>
My java code:
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;
}
You’re creating the stream in the constructor of the bean instead of in the action method associated with the
<p:commandButton>. The symptoms indicate that the bean is placed in a broader scope than the request scope. The constructor is only called upon bean’s construction, not on every HTTP request. If the bean is put in the request scope, then the constructor is called on every HTTP request.You have 2 options:
Put the bean in the request scope.
Create the stream in an action method instead and bind it to
<p:commandButton action>.