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.
To upload file using JAX-RS API, we are using jersey implementation. Click me to download jersey jar files. To upload file through jersey implementation, you need to provide extra configuration entry in web.xml file. Let's see the complete code to upload file using RESTful JAX-RS API.
JAX-RS is Java API for RESTful Web Services (JAX-RS) is a Java programming language API spec that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern. There are two main implementations of JAX-RS API:
The @Consumes (MediaType.MULTIPART_FORM_DATA) is used to provide information of the file upload. To upload file using JAX-RS API, we are using jersey implementation. Click me to download jersey jar files. To upload file through jersey implementation, you need to provide extra configuration entry in web.xml file.
Create s REST service in Java to upload a file using JAX-RS, Jersey on Tomcat server. Clone or download code from Github repo. Instructions on how to build, deploy are included in README file. Create a file ApplicationConfig under your root java source folder. and register MultiPartFeature class. Add the below dependency in pom.xml file.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With