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

2022-01-21 00:00:00 filestream java jax-rs jersey outputstream

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

I want to return a zipped file from my server-side java using JAX-RS to the client.

我尝试了以下代码,

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

但我遇到了如下异常,

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

出了什么问题,我该如何解决?

What is wrong and how can I fix this?

推荐答案

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

You are delegating in Jersey the knowledge of how to serialize the ZipOutputStream. So, with your code you need to implement a custom MessageBodyWriter for ZipOutputStream. Instead, the most reasonable option might be to return the byte array as the entity.

您的代码如下所示:

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

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

In this example I use FileUtils from Apache Commons IO to convert File to byte[], but you can use another implementation.

相关文章