1

I am using spring 4 web-mvc to create a rest api. I have a gigantic csv file that I want to stream. In python I can do very simple:

from flask import Response

@app.route('/large.csv')
def generate_large_csv():
    def generate():
        for row in iter_all_rows():
            yield ','.join(row) + '\n'
    return Response(generate(), mimetype='text/csv')

What is the equivalent in Spring 4? Is this possible?

1 Answer 1

3

Below is pseudo code as a hint for you:

@RequestMapping(value = "/large.csv", method = GET, produces = "text/csv")
@ResponseStatus(value = HttpStatus.OK)
public void streamLargeCSV(OutputStream output) {
    InputStream is = new FileInputStream(csvFile);
    int read=0;
    byte[] bytes = new byte[1024 * 4];  //size per read

    while((read = is.read(bytes))!= -1){
        output.write(bytes, 0, read);
        output.flush();  //may change flush rate to more rows/flush
    }
    output.close()
}
Sign up to request clarification or add additional context in comments.

4 Comments

My csv is 16GB, my memory is 4GB. My memory will not crash from this right?
Basically you need to read your file as streaming as well. Let me update my answer to read from file.
In spring usually I return something like a String or something, but in your code you use a "void", would it actually return to the browser without using any return statement?
As for this one, we inject OutputStream output. Therefore, no return value required.

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.