如何使用Jersey下载PDF文件?

est*_*rim 15 java file download jersey

我需要使用Jersey Web Services下载pdf文件我已经执行以下操作,但收到的文件大小始终为0(零).

 @Produces({"application/pdf"})
 @GET
 @Path("/pdfsample")
 public Response getPDF()  {

    File f = new File("D:/Reports/Output/Testing.pdf");
    return Response.ok(f, "application/pdf").build();

 }
Run Code Online (Sandbox Code Playgroud)

请帮忙做正确的方法,谢谢!!

Jos*_*ert 12

Mkyong总是提供.看起来你唯一缺少的是正确的响应头.

http://www.mkyong.com/webservices/jax-rs/download-excel-file-from-jax-rs/

@GET
@Path("/get")
@Produces("application/pdf")
public Response getFile() {
    File file = new File(FILE_PATH);
    ResponseBuilder response = Response.ok((Object) file);
    response.header("Content-Disposition","attachment; filename=test.pdf");
    return response.build();
}
Run Code Online (Sandbox Code Playgroud)


Qwe*_*rky 3

你不能只给出 aFile作为实体,它不会那样工作。

您需要自己读取该文件并将数据(作为byte[])作为实体。

编辑:
您可能还想查看流式输出。这有两个优点;1) 它允许您使用服务文件,而无需读取整个文件的内存开销;2) 它立即开始向客户端发送数据,而无需您先读取整个文件。有关流式处理的示例,请参阅/sf/answers/245259311/ 。