I'm trying to use the p:fileDownload
in my project to download csv files.
I tried to use the example in the ShowCase but it didn't workd for me since the file is generated dynamic when the user clicks a button.
The logic is currently implemented in the getter-function but I also tried to place the logic in a separate function and pass the value to the variable. In both cases I received the file but the content was empty. If I debug I see that the data is available.
My Function
StreamedContent printDocFile;
//getter
public StreamedContent getPrintDocFile() {
List<String> rows = //get information from DB
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
CSVWriter csvWriter = new CSVWriter(writer);
for (String row : rows) {
String[] rowData = row.split(",");
csvWriter.writeNext(rowData);
}
csvWriter.close();
byte[] csvData = outputStream.toByteArray();
ByteArrayInputStream stream = new ByteArrayInputStream(csvData);
printDocFile = DefaultStreamedContent.builder()
.name("test.csv")
.contentType("text/csv")
.stream(() -> stream)
.build();
stream.close();
return printDocFile;
}
The button in the View
<p:commandButton id="downloadBtn"
value="Print"
update="form:msg">
<p:fileDownload value="#{myController.printDocFile}"/>
</p:commandButton>
If I use the same code but instead p:fileDownload I use ExternalContext with ajax="false" the file has content.