Brams
Brams

Reputation: 309

JAX-RS Accept Images as input

For quite some time now, I've been developing JAX-RS web services for my development needs. All the methods that I've written so far accept java Strings or primitive types as input.

An example of such a method:

@POST  
@Path("MyMethod")  
@Produces(MediaType.APPLICATION_JSON)  
public String MyMethod(@FormParam("username")String username, @FormParam("password")String passowrd)

What I'm trying to do now is accept images as input. I read a lot of articles regarding this. Some suggested accepting the base64 encoding as input and others suggested accepting an actual InputSteam.

However, i'm yet to see a full blown example on how to accept an InputStream. I read about the @consumer annotation and @Provider but i still can't wrap my head around it. Is there an article, documentation or an example that somehow guides me toward this? i.e. A step by step process on how to implement rather than displaying theory.

I know that the base64 encoding works but out of curiosity i would like to know how the other approach works as well...Thanks in advance.

Upvotes: 10

Views: 12218

Answers (2)

Torsten Römer
Torsten Römer

Reputation: 3926

Probably not the preferred but a simple way to combine InputStream with one or more path parameters:

@POST
@Path("page/{page}")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces("image/jpeg")
public StreamingOutput generatePage(final InputStream inputStream, @Context UriInfo uriInfo) {
    final int page = Integer.parseInt(uriInfo.getPathParameters().getFirst("page"));
    return (outputStream) -> {
        service.generatePage(page, inputStream, outputStream);
    };
}

Upvotes: 0

yegor256
yegor256

Reputation: 105053

This should work:

import org.apache.commons.io.IOUtils;
@POST
@Path("MyMethod") 
@Consumes("*/*") // to accept all input types 
public String MyMethod(InputStream stream) {
    byte[] image = IOUtils.toByteArray(stream);
    return "done";
}

Upvotes: 8

Related Questions