Zack
Zack

Reputation: 13952

How do I serve csv files using java spark?

I am using spark to run the server side for a web application I am writing. I searched the documentation a bit, but I came up empty.. is there a way to serve data to the frontend such that it automatically downloads for the user as a csv file? My data that I am attempting to serve as csv looks something like this.

// example data... returned by "getData()"

JSONArray test = new JSONArray()
    .put(
        new JSONArray().put("foo").put("bar")
    )
    .put(
        new JSONArray().put(1).put(2)
    );


// route
get("/csv/:path", "application/json", (req, res) -> {
    res.type("text/csv");
    JSONArray reply = getData(req);
    return data; 
});

I was taking a look at the ResponseTransformers section of the documentation, but I couldn't figure out how to serve my data as a downloadable csv file instead of a json object. I'm assuming the ResponseTransformer would somehow need to be subclassed, but I couldn't find an example to do what I want. Could anyone provide me with an example, or point me in the direction of some docs that explain how to do this?

EDIT : I was able to, on the javascript side, call my route like this.

window(route);

which allowed me to select a program on my computer to download the response. However, the data looks like this in notepad

[["foo","bar"],[1,2]]

So, close.. but not quite a csv file. I was hoping the output would look more like this.

foo,bar
1,2

Upvotes: 0

Views: 953

Answers (1)

Laercio Metzner
Laercio Metzner

Reputation: 1359

I think you could use a StringBuilder to render your csv file, as this answer does. I also think that the second parameter of your request "application/json" could also be removed. It would look like this:

// route
get("/csv/:path", (req, res) -> {
res.type("text/csv");
    StringBuilder sb = new StringBuilder();
    sb.append("id");
    sb.append(',');
    sb.append("Name");
    sb.append('\n');

    sb.append("1");
    sb.append(',');
    sb.append("Zack");
    sb.append('\n');
    return sb.toString(); 
});

Upvotes: 1

Related Questions