Uploading any number of files using Retrofit Multipart Request

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.

. . .

Comments (2)

Add Your Comment

  • Atul Motors
    Hi, I have to send audio files like every 10 min. Similar files. Audios only. How can I do it?
    • Vedesh Kumar
      Hello Atul, You can use the same code for the audios as well. All you need to do is change the MediaType.

      And to send it after every 10 mins, You will have to start a service and you can get the task done.

  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close