16

我需要使用 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();

 }

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

4

3 回答 3

13

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();
}
于 2013-07-26T17:55:09.367 回答
2

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

您需要自己阅读文件并将数据(作为 a byte[])作为实体提供。

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

于 2012-12-14T10:45:51.497 回答
1

对于未来的访客,

这将找到位于传递的 ID 处的 blob,并将其作为 PDF 文档在浏览器中返回(假设它是存储在数据库中的 pdf):

@Path("Download/{id}")
@GET
@Produces("application/pdf")
public Response getPDF(@PathParam("id") Long id) throws Exception {
    Entity entity = em.find(ClientCase.class, id);
    return Response
            .ok()
            .type("application/pdf")
            .entity(entity.getDocument())
            .build();
}
于 2016-02-19T07:35:47.507 回答