Search code examples
javarestfile-uploadjersey

Accessing parts of a multipart/form-data post request in a Java REST web service


I have a multipart form which is supposed to upload a file as well as some parameters. It looks like this:

<form id="upload" action="http://localhost:9998/test" method="post" enctype="multipart/form-data">
    <input name="inputfile" type="file" size="50" accept="application/octet-stream">
    <input name="someparameter" type="text" size="10">
    <input type="submit" value="Go!">
</form>

The web service looks like this:

@Path("/test")
public class ServiceInterface {
    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public void execute(@FormParam(value="someparameter") String param) {
        System.out.println(param);
    }
}

When submitting the form, the value for "someparameter" is always reported as null although in the form I entered a value.

My questions are:

  1. What is wrong with the above code?
  2. How would I access the file which is transmitted with the form?

I am using Jersey 1.10.


Solution

  • Ok, after googling quite a few hours I found the error in my code.

    You have to use the annotation @FormDataParam instead of @FormParam.

    The resulting code looks like this:

    @Path("/test")
    public class ServiceInterface {
        @POST
        @Consumes(MediaType.MULTIPART_FORM_DATA)
        public void execute(
                       @FormDataParam("someparameter") String param
                       @FormDataParam("inputfile") File inputfile
                           )
        {
            System.out.println(param);
        }
    }