Serving Files using Jersey Web Service (JAX-RS)

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?

3 thoughts on “Serving Files using Jersey Web Service (JAX-RS)”

  1. After streaming a large file to the output and returning the Response, how does one delete or clean-up the files?

      1. tried that file is getting deleted and and I am getting error
        FileProvider E org.apache.wink.common.internal.providers.entity.FileProvider$1 run The system cannot read the C:\IBM\WebSphere\AppServer\profiles\AppSrv03\listProducts2018.March.15 AD 03-32-53.836 AM.xlsx file to serve as a HTTP response. The file is not readable or is a directory. Verify that the file exists and the correct file permissions are set.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top