Multiple files upload with request body using spring boot and test using Postman

Pankaj Kumar
2 min readSep 23, 2019

In one of my previous projects we came across a requirement where we had to submit a UI form with multiple files uploaded. Technically it is also known as multipart request. Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file uploads and for transferring data of several types in a single request (for example, a file along with a JSON object)

We were using Angular 7 for front-end and Java/Spring boot for back-end. While I was working on java part I started to write a REST endpoint that could accept multiple files and request body(JSON data). I was able to write the REST endpoint quickly. However UI code was not ready yet so I decided to test using swagger. To my surprise swagger had a bug(and I believe it still has the bug). It didn’t support multipart mixed request as It always showed up bad request error upon hitting the REST endpoint.

Then I tried to test using Postman but how do I send files and request body together? I can send files using form-data while request body as raw JSON but there is no way to to use both of them together. The body type can be either form-data or raw. After lot of research I figured out how to overcome this hurdle. Its bit tricky :)

Here is sample Java/Spring code to expose a REST endpoint to accept multiple files along with request body with method type POST

Java code for REST API

Here is the Postman Request

Postman Request to hit REST API

The trick here is to create a json file for request body data(job profile in our case) and keep the headers blank. Upload the json file similar to other files. By doing this Postman detects that it is multipart request and fills the boundary parameter of request itself and creates a multipart/mixed request.

If you are writing angular code to hit the API. Trick is to explicitly set Content-Type: undefined. By doing this browser will fill in boundary parameter of request itself.

Happy coding…..

--

--