Rolando
Rolando

Reputation: 62616

How to stream large csv in Spring4 rest api?

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?

Upvotes: 1

Views: 4015

Answers (1)

Wenbing Li
Wenbing Li

Reputation: 12952

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()
}

Upvotes: 3

Related Questions