0

I need to send post request using java test to this rest function :

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@PathVariable Long ownerId, @RequestBody MultipartFile file,
        HttpServletResponse response) throws IOException {
//Some function
}

this is my trial:

File file = new File("filePath");
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE);
WebResource webResource = createResourceClient("restPath", user);
ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, fileDataBodyPart);

and the error says:

"The current request is not a multipart request"

Yara Ameen
  • 21
  • 5
  • I haven't tested, but I am not sure if you can send `FileDataBodyPart` by itself. You may need to wrap it in `MultiPart`. See [this post](http://stackoverflow.com/a/34646196/2587435) for an example of what I mean. – Paul Samsotha Feb 11 '16 at 14:13
  • Thanks so much it works :)) – Yara Ameen Feb 14 '16 at 07:42
  • Possible duplicate of [Jersey REST Client : Posting MultiPart data](http://stackoverflow.com/questions/28754766/jersey-rest-client-posting-multipart-data) – J. Chomel Mar 17 '17 at 07:10

1 Answers1

2

The below piece of code will send both the file and the ContentDispostion to the REST API.

FormDataBodyPart formPart = new FormDataBodyPart(FormDataContentDisposition.name("file").fileName("YourFileName").build(),
            inputStream,MediaType.APPLICATION_OCTET_STREAM_TYPE);

    MultiPart multipart = new FormDataMultiPart().bodyPart(formPart);
    resource = resource.path("Your Rest api path");
ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, multipart);