问题描述
我想使用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?
推荐答案
您正在泽西岛委派如何序列化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 将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文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!