Search code examples
javaresteasy

How to send Multiparfile and other formparams as @MultipartForm in java


On the serverside the interface looks like:

@RequestMapping(value = "doSomething", method = RequestMethod.POST,
        headers = {"content-type=multipart/mixed","content-type=multipart/form-data"}, produces = MediaType.TEXT_PLAIN_VALUE)
ResponseEntity<String> doSomething(
        @RequestPart("name") String name,
        @RequestPart("file") MultipartFile file,
        @RequestPart("type") String type
);

And on clientside the interfce is:

@POST
@Path("doSomething")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.MULTIPART_FORM_DATA)
String doSomething(@MultipartForm MultipartBody body);

With the ResteasyClientBuilder i use this interface with the MultipartBody:

public class MultipartBody {

    @FormParam("name")
    @PartType(MediaType.TEXT_PLAIN)
    public String name;

    @FormParam("file")
    @PartType(MediaType.APPLICATION_OCTET_STREAM)
    public InputStream file;

    @FormParam("type")
    @PartType(MediaType.TEXT_PLAIN)
    public String type;
}

But i got 400 bad request. And on serverside an Exception occurs:

[org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]

The call of the client looks like.

Body: --02d16fb7-e89e-4847-adaa-d64db0c86700
Content-Disposition: form-data; name="file"
Content-Type: application/octet-stream

testerito
--02d16fb7-e89e-4847-adaa-d64db0c86700
Content-Disposition: form-data; name="name"
Content-Type: text/plain

test
--02d16fb7-e89e-4847-adaa-d64db0c86700
Content-Disposition: form-data; name="type"
Content-Type: text/plain

test
--02d16fb7-e89e-4847-adaa-d64db0c86700-- 

What im doing wrong?


Solution

  • Finally I found a solution. I had to define a filename for the file itself. The MultiPartBody has to look like:

    public class MultipartBody {
    
    @FormParam("name")
    @PartType(MediaType.TEXT_PLAIN)
    public String name;
    
    @FormParam("file")
    @PartType(MediaType.APPLICATION_OCTET_STREAM)
    @PartFilename("test.txt")
    public InputStream file;
    
    @FormParam("type")
    @PartType(MediaType.TEXT_PLAIN)
    public String type;
    

    }

    So in my case I had to set the @PartFilename annotiation