Download image file from JAX-RS

来源:互联网 发布:java 接口开发demo 编辑:程序博客网 时间:2024/06/13 05:39

In JAX-RS, for user to download an image file, annotate the method with @Produces("image/image-type") :

  • Put @Produces(“image/png”) on service method, for “png” image.
  • Set “Content-Disposition” in Response header to prompt a download box.

1. Download Image in JAX-RS

Full example to download an image file from JAX-RS.

import java.io.File;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.core.Response;import javax.ws.rs.core.Response.ResponseBuilder;@Path("/image")public class ImageService {    private static final String FILE_PATH = "c:\\mkyong-logo.png";    @GET    @Path("/get")    @Produces("image/png")    public Response getFile() {        File file = new File(FILE_PATH);        ResponseBuilder response = Response.ok((Object) file);        response.header("Content-Disposition",            "attachment; filename=image_from_server.png");        return response.build();    }}

2. Demo

Access this URI pattern : “/image/get“.

Figure : Image file “c:\\mkyong-logo.png” from server is prompted for user to download, with a new file name “image_from_server.png“
download image from server

0 0
原创粉丝点击