Uploading a file with a filename with Spring RestTemplate

Malte Finsterwalder
red6
Published in
2 min readFeb 15, 2019

When you google, you will find several examples of, how to upload a file with Spring RestTemplate. A lot of them are wrong in a small but important detail. They don’t send the filename in the correct format.

File upload is sent via Multipart Form Data. This format allows to embed multiple independent information in the body of an HTTP Post Request.

A correct file upload request would look like this:

HTTP Header:

Content-Type: multipart/form-data; boundary=ABCDEFGHIJKLMNOPQ

HTTP Body:

--ABCDEFGHIJKLMNOPQ
Content-Disposition: form-data; name="file"; filename="my.txt"
Content-Type: application/octet-stream
Content-Length: ...
<...file data in base 64...>
--ABCDEFGHIJKLMNOPQ--

There can be multiple sections like this in the body with additional data, when more data needs to be posted to the server, like multiple files or other metadata. The Content-Type could also be adjusted. application-octet-stream is the default Spring uses for byte[] data.

To produce a request like this with Spring RestTemplate, you need to write the following code:

Most solutions you find will not use the embedded HttpEntity, but will just add two entries to the MultiValueMap for the body like so:

MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("filename", "my.txt");
body.add("file", new ByteArrayResource(someByteArray));

This produces a different request body, where the file and the filename are embedded in two different sections like this:

--ABCDEFGHIJKLMNOPQ
Content-Disposition: form-data; name="filename"
Content-Type: text/plain;charset=UTF-8
Content-Length: 6
my.txt
--ABCDEFGHIJKLMNOPQ
Content-Disposition: form-data; name="file"
Content-Type: application/octet-stream
Content-Length: ...
<...file data in base 64...>
--ABCDEFGHIJKLMNOPQ--

The receiving server will most likely not see the filename in a different section. Some servers will reject the request entirely.

So also work with the embedded HttpEntity, when uploading a file with Spring RestTemplate, to produce standard compliant multipart upload requests!

Should you get the following exception:

org.springframework.web.client.RestClientException:
No HttpMessageConverter for org.springframework.util.LinkedMultiValueMap and content type “multipart/form-data”

your are probably missing a proper message converter. You can add one to the RestTemplate with the following code snippet:

MappingJackson2HttpMessageConverter converter =
new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(
MediaType.APPLICATION_OCTET_STREAM));
restTemplate.getMessageConverters().add(converter);

--

--

Malte Finsterwalder
red6
Writer for

Software Developer, New Work Enthusiast, Interested in new Management and Leadership in Organizations