0

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

1 Answer 1

1

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(); 
});
Sign up to request clarification or add additional context in comments.

2 Comments

Follow up question... why do the new lines not appear to have an effect when I open this in notepad? When I open in windows wordpad, I see the newlines as expected. Does notepad just not bother with newlines?
There are two ways to set a line break in a file, it's a history matter. Both the characters 10 and 13 from ascii table are accepted as line breaks, and this can vary for many reasons, especially if you did not set a character encoding for the file you are returning. Try using UTF-8 like res.type("text/csv; charset=UTF-8"); and open your file in a text editor properly set to UTF-8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.