使用 JERSEY 输入和输出二进制流?
我正在使用 Jersey 来实现一个 RESTful API,该 API 主要用于检索和提供 JSON 编码的数据.但在某些情况下,我需要完成以下工作:
I'm using Jersey to implement a RESTful API that is primarily retrieve and serve JSON encoded data. But I have some situations where I need to accomplish the following:
- 导出可下载的文档,例如 PDF、XLS、ZIP 或其他二进制文件.
- 检索多部分数据,例如一些 JSON 和上传的 XLS 文件
我有一个基于 JQuery 的单页 Web 客户端,它创建对该 Web 服务的 AJAX 调用.目前,它不进行表单提交,并使用 GET 和 POST(带有 JSON 对象).我应该使用表单帖子来发送数据和附加的二进制文件,还是可以使用 JSON 和二进制文件创建多部分请求?
I have a single-page JQuery-based web client that creates AJAX calls to this web service. At the moment, it doesn't do form submits, and uses GET and POST (with a JSON object). Should I utilize a form post to send data and an attached binary file, or can I create a multipart request with JSON plus binary file?
我的应用程序的服务层当前在生成 PDF 文件时会创建一个 ByteArrayOutputStream.通过 Jersey 将此流输出到客户端的最佳方式是什么?我创建了一个 MessageBodyWriter,但我不知道如何从 Jersey 资源中使用它.这是正确的方法吗?
My application's service layer currently creates a ByteArrayOutputStream when it generates a PDF file. What is the best way to output this stream to the client via Jersey? I've created a MessageBodyWriter, but I don't know how to use it from a Jersey resource. Is that the right approach?
我一直在查看 Jersey 随附的示例,但尚未找到任何说明如何执行这些操作的任何内容.如果重要的话,我正在使用 Jersey 和 Jackson 来执行 Object->JSON 而不使用 XML 步骤,并且没有真正使用 JAX-RS.
I've been looking through the samples included with Jersey, but haven't found anything yet that illustrates how to do either of these things. If it matters, I'm using Jersey with Jackson to do Object->JSON without the XML step and am not really utilizing JAX-RS.
推荐答案
我设法通过扩展 StreamingOutput
对象来获取 ZIP 文件或 PDF 文件.下面是一些示例代码:
I managed to get a ZIP file or a PDF file by extending the StreamingOutput
object. Here is some sample code:
@Path("PDF-file.pdf/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
PDFGenerator generator = new PDFGenerator(getEntity());
generator.generatePDF(output);
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
}
PDFGenerator 类(我自己的用于创建 PDF 的类)从 write 方法获取输出流并写入该方法,而不是新创建的输出流.
The PDFGenerator class (my own class for creating the PDF) takes the output stream from the write method and writes to that instead of a newly created output stream.
不知道这是否是最好的方法,但它确实有效.
Don't know if it's the best way to do it, but it works.
相关文章