Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 501
Spring Avatar asked Feb 19 '14 09:02

Spring


People also ask

How do I download a CSV file?

Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).

Can a REST API return CSV?

There is no function in the API that will return results in CSV format. You will need to use language-level utilities to create a CSV file while generating the reports.

Can rest use CSV?

You can import data into a data source that is configured to receive CSV data by publishing CSV files through a REST service.


2 Answers

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.

like image 160
tom Avatar answered Oct 10 '22 09:10

tom


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.

like image 39
AlexR Avatar answered Oct 10 '22 09:10

AlexR