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!
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With