如何使用JAX-RS从Java服务器端返回Zip文件?

pri*_*nce 4 java outputstream jax-rs jersey filestream

我想使用JAX-RS从我的服务器端java返回一个压缩文件到客户端.

我尝试了以下代码,

@GET
public Response get() throws Exception {

    final String filePath = "C:/MyFolder/My_File.zip";

    final File file = new File(filePath);
    final ZipOutputStream zop = new ZipOutputStream(new FileOutputStream(file);

    ResponseBuilder response = Response.ok(zop);
    response.header("Content-Type", "application/zip");
    response.header("Content-Disposition", "inline; filename=" + file.getName());
    return response.build();
}
Run Code Online (Sandbox Code Playgroud)

但我得到的例外情况如下,

SEVERE: A message body writer for Java class java.util.zip.ZipOutputStream, and Java type class java.util.zip.ZipOutputStream, and MIME media type application/zip was not found
SEVERE: The registered message body writers compatible with the MIME media type are:
*/* ->
  com.sun.jersey.core.impl.provider.entity.FormProvider
Run Code Online (Sandbox Code Playgroud)

有什么问题,我该如何解决这个问题?

小智 10

您在Jersey中委派了有关如何序列化ZipOutputStream的知识.因此,使用您的代码,您需要为ZipOutputStream实现自定义MessageBodyWriter.相反,最合理的选择可能是将字节数组作为实体返回.

您的代码如下:

@GET
public Response get() throws Exception {
    final File file = new File(filePath);

    return Response
            .ok(FileUtils.readFileToByteArray(file))
            .type("application/zip")
            .header("Content-Disposition", "attachment; filename=\"filename.zip\"")
            .build();
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,我使用Apache Commons IO中的 FileUtils 将File转换为byte [],但您可以使用其他实现.


小智 7

您可以将附件数据写入 StreamingOutput 类,Jersey 将从中读取。

@Path("/report")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response generateReport() {
    String data = "file contents"; // data can be obtained from an input stream too.
    StreamingOutput streamingOutput = outputStream -> {
        ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(outputStream));
        ZipEntry zipEntry = new ZipEntry(reportData.getFileName());
        zipOut.putNextEntry(zipEntry);
        zipOut.write(data); // you can set the data from another input stream
        zipOut.closeEntry();
        zipOut.close();
        outputStream.flush();
        outputStream.close();
    };

    return Response.ok(streamingOutput)
            .type(MediaType.TEXT_PLAIN)
            .header("Content-Disposition","attachment; filename=\"file.zip\"")
            .build();
}
Run Code Online (Sandbox Code Playgroud)


Opa*_*pal 1

我不确定在泽西岛是否有可能只返回一个流作为带注释的方法的结果。我认为应该打开流并将文件的内容写入流。看看这篇博文。我想你应该实现类似的东西。