Spring
Spring

Reputation: 11865

Download CSV file via Rest

Using OpenCSV, I can successfully create a CSV file on disc, but what I really need is to allow users download the CSV with a download button, I don't need to save on disk, just download. Any ideas?

@GET
@Path("/downloadCsv")
public Object downloadCsv() {
        CSVWriter writer;
        FileWriter wr; 
      //Or should I use outputstream here?   
        wr= new FileWriter("MyFile.csv");
        writer = new CSVWriter(wr,',');
        for (Asset elem: assets) {
            writer.writeNext(elem.toStringArray());
        }
        writer.close();


}

EDIT: I do NOT want to save/read file on disc EVER

Upvotes: 7

Views: 56302

Answers (3)

Reeebuuk
Reeebuuk

Reputation: 1381

            response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
            response.setContentType("text/csv");
            OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");

            List<String[]> result = iSmsExportService.csvExport(columnNames);
            CSVWriter csvWriter = new CSVWriter(osw, ';');
            csvWriter.writeAll(result);
            csvWriter.flush();
            csvWriter.close();

Downloading of CSV file has started after this.

Upvotes: 4

tom
tom

Reputation: 2712

To force "save as", you need to set the content disposition HTTP header in the response. It should look like this:

Content-Disposition: attachment; filename="whatever.csv"

It looks like you're using JAX-RS. This question shows how to set the header. You can either write the CSV to the HTTP response stream and set the header there or return a Response object like so:

return Response.ok(myCsvText).header("Content-Disposition", "attachment; filename=" + fileName).build();

You do not need to write to a File object in the middle of this process so can avoid writing to disk.

Upvotes: 19

AlexR
AlexR

Reputation: 115418

First, you code cannot be compiled, right? Method downloadCsv() declares return type Object but does not return anything.

I'd change the declaration to String downloadCsv() and return the content of CSV as string. To do this use StringWriter instead of FileWriter and then say return wr.toString().

The only thing that is missing here is content type. You annotate your method as @Produces({"text/csv"}).

I think, that's it.

Upvotes: 4

Related Questions