Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading a CSV file using JSF

I don't know how to download a CSV file. The CSV will be generated at runtime. Do I need to save the file in the tomcat WEB-INF directory first? I'm using JSF 1.2.

By the way, what's the favored JSF component for this kind of task?


Edit (05.05.2012 - 15:53)

I tried the solution BalusC stated in his first link, but if I click on my commandButton the content of the file is displayed on the webpage. Maybe there's a problem with the mimetype?

xhtml-file:

<a4j:form>
    <a4j:commandButton action="#{surveyEvaluationBean.doDataExport}" value="#{msg.srvExportButton}" />
</a4j:form>

main bean:

    public String doDataExport() {

    try {
        export.downloadFile();  
    } catch (SurveyException e) {
        hasErrors = true;
    }
    return "";
}

export-bean:

public void downloadFile() throws SurveyException {

    try {

        String filename = "analysis.csv";

        FacesContext fc = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setContentType("text/comma-separated-values");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

        OutputStream output = response.getOutputStream();

        // writing just sample data
        List<String> strings = new ArrayList<String>();

        strings.add("filename" + ";" + "description" + "\n");
        strings.add(filename + ";" + "this is just a test" + "\n");

        for (String s : strings) {
            output.write(s.getBytes());
        }

        output.flush();
        output.close();

        fc.responseComplete();

    } catch (IOException e) {
        throw new SurveyException("an error occurred");
    }
}

Edit (05.05.2012 - 16:27)

I solved my problem. I have to use <h:commandButton> instead of <a4j:commandButton> and now it works!

like image 534
yves.beutler Avatar asked Oct 08 '22 22:10

yves.beutler


1 Answers

Do I need to save the file in the tomcat WEB-INF directory first?

No, just write it straight to the HTTP response body as you obtain by ExternalContext#getResponseOutputStream() after having set the proper response headers which tells the browser what it's going to retrieve.

Do the math based on the concrete examples found in the following answers:

  • How to provide a file download from a JSF backing bean?
  • JSP generating Excel spreadsheet (XLS) to download

Basically:

List<List<Object>> csv = createItSomehow();
writeCsv(csv, ';', ec.getResponseOutputStream());

By the way, what's the favorite jsf-component for this kind of task?

This is subjective. But anyway, we're using <p:dataExporter> to full satisfaction.

like image 126
BalusC Avatar answered Oct 13 '22 10:10

BalusC