Question

I've got two outputstreams (filled with data by jasper reports to generate one excel and one csv). The filling of the outputstreams works just fine, but now I have to pack both "streams / files" in to a zip to be downloaded. How could I do this?

The code to download just one file is the following:

public void exportInternalEvaluation() {
    exportStats(ExportingValues.STATISTICS_INTERNAL_EVALUTATION, EXCEL_NAME, solvedDossiers,
            "application/vnd.ms-excel");
}

private void exportStats(ExportingValues exportingValues, String fileName, Collection < ? > collection,
        String contentType) {
    OutputStream os = null;
    try {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();

        ec.responseReset();
        ec.setResponseContentType(contentType);
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        os = ec.getResponseOutputStream();

        statsLocal.generateStatStream(collection, os, exportingValues.getJasperFileName(null),
                exportingValues.getReportingType());

        fc.responseComplete();
    } 
}

This code is setting the content type to excel and lets me download the file. I've already found the following:

        ZipOutputStream zos = new ZipOutputStream(os);  //create a zipOutputStream with my responseOutputStream

but then I'm stuck on creating the ZipEntries. How can I create 2 entries (1 excel and 1 csv) from 2 different streams?

EDIT: And I don't really want to create 2 tempfiles and add them to the zip. I'd like to find a way to "add" the 2 outputstreams to a zip file creating 2 different files without having to create them first (even tempFiles..). If possible though...

Was it helpful?

Solution

You can decorate the response stream with a ZipOutputStream and have your generator code write to that ensuring that you create new entries between each call:

try (OutputStream os = ec.getResponseOutputStream();
    ZipOutputStream zout = new ZipOutputStream(os)) {
  zout.putNextEntry(new ZipEntry("foo.xls"));
  generate(zout, "Excell gen call args");
  zout.closeEntry();
  zout.putNextEntry(new ZipEntry("foo.csv"));
  generate(zout, "CSV gen call args");
  zout.closeEntry();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top