How can I return a Zip file from my Java server-side using JAX-RS?(如何使用 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 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 JAX-RS 从我的 Java 服务器端返回 Zip 文件?
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01