9

I have created a rest call that responds back with the CSV file using Jersey.

rest call code is:

@GET
@Path("/ReportWithoutADEStatus")
@Produces({ "application/ms-excel"})
public Response generateQurterlyReport(){
    QuarterlyLabelReport quartLabelReport = new QuarterlyLabelReport();
    String fileLoc=quartLabelReport.generateQurterlyLblRep(false);
    File file=new File(fileLoc);
    return Response.ok(fileLoc,"application/ms-excel")
            .header( "Content-Disposition","attachment;filename=QuarterlyReport_withoutADE.csv")
            .build();
}

The above code reads a csv file created in a temp location and responds that csv using rest call. This is perfectly working fine. But now the requirement has changed. stream the file content in memory and respond that in csv format from Rest API.
I have never done streaming to a file in memory and responding back the content in REST.

Can somebody help me with this?

Thanks in advance.

1 Answer 1

15

You need to use a StreamingResponse as your response entity. In my projects I've made a simple method to return on of these from a byte array. You just have to ready the file into a byte are first, then call this:

private StreamingOutput getOut(final byte[] excelBytes) {
    return new StreamingOutput() {
        @Override
        public void write(OutputStream out) throws IOException, WebApplicationException {
            out.write(excelBytes);
        }
    };
}

Then in your main method you would something like:

return Response.ok(getOut(byteArray)).build(); //add content-disp stuff here too if wanted
1
  • Is it possible to do with @POST method.
    – spr
    Dec 26, 2016 at 14:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.