Nov 10, 2018

Example of file downloading in JSF

Download file in JSF:
public void download() throws IOException {

        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        ec.responseReset(); //Clears any data that exists in the buffer as well as the status code and headers.
        ec.setResponseContentType("application/octet-stream");

        String sFileName = "i88.ca-report.csv";

        ec.setResponseHeader("Content-Disposition", "attachment; filename=" + sFileName);

        OutputStream out = ec.getResponseOutputStream();
        StringBuilder writer = new StringBuilder();
        byte[] bytes;

        writer.append("it.i88.ca Report");

        bytes = writer.toString().getBytes();

        out.write(bytes);
        out.flush();
        out.close();

        FacesContext.getCurrentInstance().responseComplete(); // You definitely need this so that JSF knows it is done and will not navigate and restore response. 
    }