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

时间:2014-03-13 19:32:06

标签: file rest jersey ejb 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

但他们都没有工作。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

application / octet-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>

发出请求时:

发送标题为&#34;接受&#34;值为&#34; application / octet-stream&#34; 以及#34; Accept-Encoding&#34;值为&#34; gzip&#34;