9

我创建了一个使用 Jersey 以 CSV 文件响应的休息呼叫。

休息调用代码是:

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

上面的代码读取在临时位置创建的 csv 文件,并使用 rest 调用响应该 csv。这是完美的工作正常。但现在要求发生了变化。流式传输内存中的文件内容,并从 Rest API 以 csv 格式响应。
我从来没有完成流式传输到内存中的文件并响应 REST 中的内容。

有人可以帮我吗?

提前致谢。

4

1 回答 1

15

您需要使用 StreamingResponse 作为响应实体。在我的项目中,我做了一个简单的方法来从字节数组中返回这些。您只需要先将文件准备成一个字节,然后调用:

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

然后在你的主要方法中,你会是这样的:

return Response.ok(getOut(byteArray)).build(); //add content-disp stuff here too if wanted
于 2013-08-20T18:59:51.593 回答