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

一曲冷凌霜 提交于 2019-12-01 19:29:28

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.

In Jersey 2.16 file download is very easy

Below is the example for the ZIP file

@GET
@Path("zipFile")
@Produces("application/zip")
public Response getFile() {
    File f = new File(ZIP_FILE_PATH);

    if (!f.exists()) {
        throw new WebApplicationException(404);
    }

    return Response.ok(f)
            .header("Content-Disposition",
                    "attachment; filename=server.zip").build();
}

You can write the attachment data to StreamingOutput class, which Jersey will read from.

@Path("/report")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response generateReport() {
    String data = "file contents"; // data can be obtained from an input stream too.
    StreamingOutput streamingOutput = outputStream -> {
        ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(outputStream));
        ZipEntry zipEntry = new ZipEntry(reportData.getFileName());
        zipOut.putNextEntry(zipEntry);
        zipOut.write(data); // you can set the data from another input stream
        zipOut.closeEntry();
        zipOut.close();
        outputStream.flush();
        outputStream.close();
    };

    return Response.ok(streamingOutput)
            .type(MediaType.TEXT_PLAIN)
            .header("Content-Disposition","attachment; filename=\"file.zip\"")
            .build();
}

I'm not sure I it's possible in Jersey to just return a stream as result of annotated method. I suppose that rather stream should be opened and content of the file written to the stream. Have a look at this blog post. I guess You should implement something similar.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!