How to set response header in JAX-RS so that user sees download popup for Excel?

后端 未结 3 458
慢半拍i
慢半拍i 2020-12-01 03:02

I wrote code that generate Excel file using REST JAX-RS and I confirmed that the generated Excel file is in GlassFish server directory.

But my goal is when user clic

3条回答
  •  天涯浪人
    2020-12-01 03:14

    @Context ServletContext ctx;
    @Context private HttpServletResponse response;
    
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    @Path("/download/{filename}")
    public StreamingOutput download(@PathParam("filename") String fileName) throws Exception {
        final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");
        return new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException,
                    WebApplicationException {
                Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output));
            }
        };
    }
    

提交回复
热议问题