13

Goal: Post Image using RestTemplate

Currently using a variation of this

MultiValueMap<String, Object> parts = new
LinkedMultiValueMap<String, Object>();
parts.add("field 1", "value 1");
parts.add("file", new
ClassPathResource("myFile.jpg"));
template.postForLocation("http://example.com/myFileUpload", parts); 

Are there any alternatives? Is POSTing a JSON that contains a base64 encoded byte[] array a valid alternative?

2 Answers 2

16

Yep, with something like this I guess

If the image is your payload and if you want to tweak the headers you can post it this way :

HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/jpeg");
InputStream in = new ClassPathResource("myFile.jpg").getInputStream();

HttpEntity<byte[]> entity = new HttpEntity<>(IOUtils.toByteArray(in), headers);
template.exchange("http://example.com/myFileUpload", HttpMethod.POST, entity , String.class);

Otherwise :

InputStream in = new ClassPathResource("myFile.jpg").getInputStream();
HttpEntity<byte[]> entity = new HttpEntity<>(IOUtils.toByteArray(in));
template.postForEntity("http://example.com/myFileUpload", entity, String.class);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the code- it really helped me understand how this entire thing works
2

Ended up turning the Bitmap into a byte array and then encoding it to Base64 and then sending it via RestTemplate using Jackson as my serializer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.