Posted on 3 Comments

Serving Files using Jersey Web Service (JAX-RS)

Jersey Logo

There are a lot of tutorials out there explaining how to send binary data (i.e. application/octet-stream) as response for Jersey web services (Java JAX-RS). Two possible solutions are based on either returning a Response or StreamingObject containing the appropriate binary data stream.

Below you find a simple example for both scenarios:

//either inject response via context
private HttpServletResponse response;

//or return Response as shown below

 * @param content
 * @return
@Consumes("text/plain; charset=UTF-8")
public Response getAttachment(
  @QueryParam("file") String fileName) {
  try {
    if (fileName == null) {
      System.err.println("No such item");
      return Response.status(Response.Status.BAD_REQUEST).build();

    // either set response injected above
    //response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    //TODO: write file content to response.getOutputStream();
    //return response;

    // OR: use a custom StreamingOutput and set to Response
    StreamingOutput stream = new StreamingOutput() {
      public void write(OutputStream output) throws IOException {
        try {
          // TODO: write file content to output;
        } catch (Exception e) {

    return Response.ok(stream, "image/png") //TODO: set content-type of your file
            .header("content-disposition", "attachment; filename = "+ fileName)

  System.err.println("No such attachment");

  return Response.status(Response.Status.BAD_REQUEST).build();

  } catch (Exception e) {
     return Response.status(Response.Status.BAD_REQUEST).build();

Additional checks have been ommitted for better readability. You should definitely check parameter fileName and not use it directly to serve files 😉

Pretty easy, right?