Posting a MultipartFile with Rest SpringBoot

Balvinder Singh
Tekraze
Published in
2 min readNov 24, 2019

Hi everyone, I will share about how to post a file as a multipart request along with other multipart parameters.

So, I was working on a project and previously I was using like RestTemplate library by spring, but the call was failing and I was not able to post data to rest API. I tried like changing header, changing the format of request body and looked over different blogs, but no use.

So what I did like, I tried to make the call from the postman and it worked. From there I used the code option to get the related code to mimic the call in java. From there I got to know about a library, OkHttp which is a rest library for java and android. I got the sample code from Postman.

Note: Generating code is a feature provided by postman. It helps by generating a code for a relevant language and give us idea on like on how it should be done in the respective language. For example i generated OkHttp code.

The sample code from the postman can be seen in the below image. (Code generator from postman)

Sample code generated by postman

So this code above you see, gave me the idea of using OkHttp in place of RestTemplate.

So let see how to use the OkHttpCode.

  1. First Initialize the OkHttp Client.
  2. Then Create Request Body by adding required multipart parameters.
  3. Creating the request by passing the API URL and request body we just created.
  4. Create a response and execute API.
  5. Handle the response and the data from Response.

Or you can see the code snippet below for the same.

Sample code for Multipart file upload with OkHttp

So this is all for now, hope this helps you and solve your problem. Stay connected for more posts.
Also, check my blog for more posts and our publication Tekraze.

--

--

Balvinder Singh
Tekraze

Open Source FullStack Developer | Blogger | Crypto Enthusiast | Gamer