Question

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?

Was it helpful?

Solution 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.

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top