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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With