如何使用 JAX-RS 从我的 Java 服务器端返回 Zip 文件? [英] How can I return a Zip file from my Java server-side using JAX-RS?

查看:34
本文介绍了如何使用 JAX-RS 从我的 Java 服务器端返回 Zip 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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.

这篇关于如何使用 JAX-RS 从我的 Java 服务器端返回 Zip 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆