POST Form Data with image using Spring Rest Template

Jairam Gauns
1 min readOct 1, 2020

--

In microservices architecture we observe that implementation of a business process involves multiple REST calls between the component services. In most of the service calls we generally Post simple data. But how do we handle complex data type like an image? How can we post an image along with simple data?

Using Spring RestTemplate let us see how to POST simple data along with an image data.

Steps to be performed:

First, set the content type to multipart/form-data

headers.setContentType(MediaType.MULTIPART_FORM_DATA);

Next, to add the file data, we pass it as a byte array. However, in our example we will make use of ByteArrayResource provided by Spring.

Note: When using ByteArrayResource, override the getFilename() method, as the default implementation returns a null.

Below example shows how to use a RestTemplate to post the data along with an image:

--

--

No responses yet