-1

I have a csv Media file , I am trying to read this csv line by line and need to Download in the browser.

response.flushBuffer(); does not seem to Start the Download. No errors observed. I can see the complete data in the Browser response tab under Network and is in correct format. Just not able to flush it.

final MediaModel media = mediaService.getMedia(catalogVersionModelHeader, mediaIdentifier);
        final Collection<File> filesHeader = mediaService.getFiles(media);

        final BufferedReader br = new BufferedReader(new FileReader(filesHeader.iterator().next()));
        String line = "";
        final CSVWriter csvWriter = new CSVWriter(getOutputWriter());
        final Map<Integer, String> data = new HashMap<>();
        int counter = 0;
        try {
            while ((line = br.readLine()) != null) {
                data.put(new Integer(counter), line);
                csvWriter.write(data);
            }
            counter++;
        } catch (final IOException ioException) {
            LOG.error(ioException);
        }

        csvWriter.close();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + "Report.csv" + "\"");
        response.getOutputStream().write(getBytes(csvWriter));
        response.flushBuffer();

        }
    public byte[] getBytes(final CSVWriter csvWriter) {
        final StringWriter stringWriter = threadLocal.get();
        return stringWriter.getBuffer().toString().getBytes();
    }

    public Writer getOutputWriter() {
        final StringWriter writer = new StringWriter();
        threadLocal.set(writer);
        return writer;
    }

No Errors Observed.

dbc
  • 104,963
  • 20
  • 228
  • 340

1 Answers1

2

You have to close the csvWriter after you have written it to the OutputStream like this -

    ....
    ....
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "Report.csv" + "\"");
    response.getOutputStream().write(getBytes(csvWriter));
    csvWriter.close();
    response.flushBuffer();  

You CSV file content is not written to the OutputStream cause you are closing it before writing it to the OutputStream. Try just changing the order of closing csvWriter.

Razib
  • 10,965
  • 11
  • 53
  • 80