Posting a MultipartFile with Rest SpringBoot

Balvinder Singh
Nov 24, 2019 · 2 min read

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.

Tekraze

The Official Publication Handle For Tekraze a team of young developers

Balvinder Singh

Written by

Senior Software Engineer at app.dehaze.io working as FullStack and DevOps. Tech Blogger at Tekraze.com. Here to share my experiences of coding with you all…

Tekraze

Tekraze

The Official Publication Handle For Tekraze a team of young developers

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade