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?

lemon
  • 9,155
  • 7
  • 39
  • 47

2 Answers2

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);
Alex B
  • 1,866
  • 22
  • 17
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.

lemon
  • 9,155
  • 7
  • 39
  • 47