In this tutorial we will discuss about download image files from JAX-RS, for user to download a file, annotate the method with @Produces("image/image-type") :
- Put @Produces("image/png") on service method, with a Response return type. It means the output is a image file.
- Set "Content-Disposition" in Response header to tell browser pop up a download box for user to download.
1. Download Image in JAX-RS
Full example to download an image file from JAX-RS.
package com.dineshonjava.ws.rest;
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;
/**
* @author Dinesh Rajput
*
*/
@Path("/employeephoto")
public class EmployeeImageService {
private static final String IMAGE_PATH = "d:\\employee_photo.png";
@GET
@Path("/get")
@Produces("image/png")
public Response getSalarySlipFile() {
File file = new File(IMAGE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=\"employee_image_photo.png\"");
return response.build();
}
}
2. Test
Deploy above JAX-RS service, access this URI pattern : "http://localhost:8181/sdnext/doj/employeephoto/get".
Figure : Image file "d:\\employee_photo.png" from server is prompt for user to download, with a new image name "employee_image_photo.png"
Download SourceCode
Download image file from JAX-RS.zip
References
1.
JAVA REST Web Services
2.
Wikipedia for REST Web Service