Image Download in Jersey JAX-RS

If one of you RESTful Web Service Endpoints built with Jersey JAX-RS needs to initiate image download, you can use the following example to let user download an image stored on your server  when they access a certain web service end point.

The below example downloads a PNG image specified by @Produces(“image/png”) but you can easily edit it and make it download image/jpg for example.

To make the image file begin downloading we need to load it into the File object and then return back a Response object with Content-Disposition added to a Response header.

JAX-RS Image Download Example

The below code example will trigger image downloading when users access /media/company-logo Web Service End Point via HTTP GET Request.

import java.io.File;
import java.io.IOException;
 
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("/media")
public class MediaEntryPoint {

    @GET
    @Path("company-logo")
    @Produces("image/png")
    public Response getCompanyLogo() throws IOException {

        String filePath = "/media/images/company-logo.png";
        File file = new File(filePath);
 
        ResponseBuilder response = Response.ok((Object) file);
        
        response.header("Content-Disposition",
                "attachment; filename=company-logo.png");
        
        return response.build();
    }
}

If you are working with JAX-RS and Jersey check out these short tutorials with code example on how to build RESTFul Web Services with JAX-RS and Jersey.

 

Leave a Reply

Your email address will not be published. Required fields are marked *