Tag: java

  • Serving Files using Jersey Web Service (JAX-RS)

    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
    @Context
    private HttpServletResponse response;
    
    //or return Response as shown below
    
    /**
     *
     * @param content
     * @return
     */
    @GET
    @Path("/attachment")
    @Consumes("text/plain; charset=UTF-8")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    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.setContentType("image/png");
        //response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        //TODO: write file content to response.getOutputStream();
        //response.getOutputStream().close();
        //return response;
    
        // OR: use a custom StreamingOutput and set to Response
        StreamingOutput stream = new StreamingOutput() {
          @Override
          public void write(OutputStream output) throws IOException {
            try {
              // TODO: write file content to output;
            } catch (Exception e) {
               e.printStackTrace();
            }
          }
        };
    
        return Response.ok(stream, "image/png") //TODO: set content-type of your file
                .header("content-disposition", "attachment; filename = "+ fileName)
                .build();
        }
      }
    
      System.err.println("No such attachment");
    
      return Response.status(Response.Status.BAD_REQUEST).build();
    
      } catch (Exception e) {
         System.err.println(e.getMessage());
         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?