java 如何使用 Jersey 下载 PDF 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13877081/
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-10-31 14:17:36  来源:igfitidea点击:

How To Download PDF file using Jersey?

javafiledownloadjersey

提问by esthrim

I need to download pdf file using Jersey Web Services i already do the following but the file size received is always 0 (zero).

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

 }

Please help to do the correct way, thanks !!

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

采纳答案by Qwerky

You can't just give a Fileas the entity, it doesn't work like that.

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

You need to read the file yourself and give the data (as a byte[]) as the entity.

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

Edit:
You might also want to look at streaming the output. This has two advantages; 1) it allows you to use serve files without the memory overhead of having to read the whole file and 2) it starts sending data to the client straight away without you having to read the whole file first. See https://stackoverflow.com/a/3503704/443515for an example of streaming.

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

回答by Joseph Helfert

Mkyong always delivers. Looks like the only thing you are missing is the correct response header.

Mkyong 总是提供。看起来您唯一缺少的是正确的响应标头。

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

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

回答by MattiasH

For future visitors,

对于未来的访客,

This will find the blob located at the passed ID and return it as a PDF document in the browser(assuming it's a pdf stored in the database):

这将找到位于传递的 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();
}