Question

I am successful posting a file to the same web service using the following:

curl -X POST http://<someUrl> -F "file=@/path/to/aFile.txt"

Now I am attempting to perform the same type of operation using Spring's RestTemplate with the caveat that I want to send a Java Object. Here is an example of what I tried:

File file = File.createTempFile("aaa","bbb");
FileUtils.writeStringToFile(file, mapper.writeValueAsString(message), "UTF-8");

MultiValueMap<String, Object> values = new LinkedMultiValueMap<String, Object>();
values.add("file", new FileSystemResource(file));

restTemplate.postForObject(URL, values, String.class);

Where mapper is an instance of Jackson's ObjectMapper (v1.9.6) and FileUtils is from Apache's Common.

The REST service requires the content type to be multipart/form-data so what I attempted to do was write the Java Object as a JSON string to a temporary file and then post the temporary file. Unfortunately I am getting an HTTP 500 Internal Server Error.

What am I doing wrong? Any suggestions as to how to do this?

Was it helpful?

Solution

Looks like I solved it. Here is what I did for reference:

File file = File.createTempFile("aaa","bbb");
FileUtils.writeStringToFile(file, mapper.writeValueAsString(message), "UTF-8");

MultiValueMap<String, Object> values = new LinkedMultiValueMap<String, Object>();
values.add("name", file.getAbsolutePath());
values.add("filename", file.getAbsolutePath());
values.add("file", new FileSystemResource(file));

restTemplate.postForObject(URL, values, String.class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top