如何使用REST(JAX-RS球衣)将文件从服务器发送到客户端



我想使用REST JERSEY(JAX-RS)从服务器端(EJB)发送文件。

我正在尝试以下代码

Public Response getFiles() {
  File file = new File(fileName);
  FileOutputStream dest = new FileOutputStream(file);
  ZipOutputStream out =  new ZipOutputStream(new BufferedOutputStream(dest));
  out.putNextEntry(new ZipEntry(fileName));
  final ResponseBuilder response = Response.ok(out);
  response.header("Content-Type", "*/*");
  response.header("Content-Disposition", "attachment; filename=" + file.getName() + ".zip");
  return response.build();
}

但是我得到了例外消息

type class java.util.zip.ZipOutputStream, and MIME media type */* was not found
SEVERE: The registered message body writers compatible with the MIME media type are:

也尝试使用"Content-Type" , "application/octet-stream", "application/x-www-form-urlencoded"multipart/form-data

尝试

但它们都没有工作。

使用application/zip

@GET
@Produces("application/zip")
public Response getZip() {
    final File f = new File("/tmp/foo.zip");
    ResponseBuilder response = Response.ok((Object) f);
    response.header("Content-Disposition", "attachment; filename=" + f.getName());
    return response.build();
}

application/offet-stream gzip

@GET
@Path("/getFiles")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFiles() {
    StreamingOutput stream = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            String filePath = "/yourFile.pdf";
            java.nio.file.Path path = Paths.get(filePath);
            byte[] data = Files.readAllBytes(path);
            output.write(data);
            output.flush();
        }
    };
    return Response.ok(stream).build();
}

和添加到Web.xml

的泽西岛过滤器
<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
    <param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>

提出请求时:

发送带有"应用程序/八位字节"的"接受"标题和"接受"的标题,其值是" gzip"

最新更新