Uploading any number of files using Retrofit Multipart Request

Updated 22 September 2017

Save

Retrofit is a very popular and great Network library for Android. Retrofit makes it easy to connect to a REST web service by translating the API into Java interfaces. In our previous blogs, we have already learned about starting with retrofit and how to upload a single file using retrofit. If you haven’t read those and want to know about it then you can follow the below provided links.

Using Retrofit library to make Http Requests

How to make a multipart request with dynamic URL using Retrofit

Now we will discuss uploading a dynamic number of files to the server. The main twist here is that you need to define @Part MultipartBody.Part file type parameter in your request.

Let us look at a sample code below for better understanding.

In the above code segment, We have defines two RequestBody type parameters and one List<MultipartBody.Part> type param. MultipartBody.Part contains the file and a List of MultipartBody.Part will contain multiple files which will be sent with the request.

Now let us create the List of files. Below is the sample code for it.

As you can see in the above code you can add string data to your request using the create function of the RequestBody class just add the MediaType as “text/plain”. To add the file, you need to get the URI of the file, create a file object with it, create a RequestBody object with the file, create MultipartBody.Part using the RequestBody object and add it to the list. You need to set the mime type in each RequestBody object according to the file.

And after creating all the requested data you can execute the request and will get the desired results.

Thank you very much. This is Vedesh Kumar signing off.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • Atul Motors
    • Vedesh Kumar (Moderator)
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home