Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

jersey - How can I return a Zip file from my Java server-side using JAX-RS?

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

I tried the following code,

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

But i'm getting exception as below,

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Your code looks like:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...