<h:commandLink action="#{myBean.streamFile}">Download</h:commandLink>
public class MyBean {
public String getStreamFile(){
byte[] file = new byte[]{};
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
response.setHeader("Content-disposition", "attachment; filename=file.ext");
response.setContentType("text/plain");
try {
response.getOutputStream().write(file);
} catch (IOException ex) {
return "go_to_an_error_page";
}
ctx.responseComplete();
return null;
}
}
When the user selects the link, either the file will be streamed to user so they may download it, or they will be redirected to an error page. You could go one step further and implement a messaging system or use the one built-in with JSF and redirect the user back to the page they attempted to download the file from.










October 13th, 2008
2 Comments at "JSF: Stream File for Download"
Thank you very much for this. I bumped into a lot of solutions that dind´t work. This was the simplest and just worked. Thanks again.
I always forget how to do this, and I always come back to this page. Thanks!
- Jim
Comment Now!