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

后端 未结 4 593
自闭症患者
自闭症患者 2021-01-19 04:12

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 Exc         


        
4条回答
  •  误落风尘
    2021-01-19 04:45

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

提交回复
热议问题