Java 球衣休息和 csv 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18342895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:43:53  来源:igfitidea点击:

jersey rest and csv response

javarestjersey-2.0jersey-1.0

提问by ram

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

我创建了一个休息调用,它使用 Jersey 以 CSV 文件进行响应。

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.

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

Can somebody help me with this?

有人可以帮我解决这个问题吗?

Thanks in advance.

提前致谢。

采纳答案by nick.stuart

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:

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

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