无法下载附件

Not able to download the attachments

我正在尝试使用 jersey restful 服务下载附件。

下面是我的代码片段:

if(entity != null) {
    ResourceStream stream = new ResourceStream(entity);
    return Response.ok(stream.getResponse(), entity.getMediatype()).header("Content-Disposition", "attachment; filename=\"" + entity.getName() + "\" ").build();
}

上面的代码 returns 下面的响应:

Apr 18, 2017 12:06:23 PM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/pdf, type=class org.glassfish.jersey.message.internal.OutboundJaxrsResponse, genericType=class org.glassfish.jersey.message.internal.OutboundJaxrsResponse.

将子资源方法上的注释设置为

@Produces(MediaType.APPLICATION_OCTET_STREAM)

并创建类似

的文件对象
File file = new File("Location of the file with file name");

并像这样发送响应

if (file.exists()) {
  ResponseBuilder builder = Response.ok(file);
  builder.header("Content-Disposition", "attachment; filename=" + file.getName());
response = builder.build();

和 return 响应

return builder;

更多信息

jersey file upload and download example