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.
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.
1 2 3 4 5 6 7 8 9 |
@Multipart @POST Observable<BaseModel> sendTrunkMultiPart( @Url String url , @Part("param1") RequestBody param1 , @Part("param2") RequestBody param2 , @Part List<MultipartBody.Part> files ); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// add the params part within the multipart request RequestBody param1 = RequestBody.create(MediaType.parse("text/plain"), "Your Text"); RequestBody param2 = RequestBody.create(MediaType.parse("text/plain"), "Your Text"); Uri photoUri = ... // get it from a file chooser or a camera intent Uri videoUri = ... // get it from a file chooser or a camera intent // create list of file parts List<MultipartBody.Part> parts = new ArrayList<>(); if (photoUri != null) { File imageFile = new File(photoUri.getPath()); RequestBody requestImageFile = RequestBody.create(MediaType.parse("image/*"),imageFile); parts.add(MultipartBody.Part.createFormData("any_name_for_the_part",imageFile.getName(),requestImageFile)); } if (videoUri != null) { File videoFile = new File(videoUri.getPath()); RequestBody requestVideoFile = RequestBody.create(MediaType.parse("video/*"),videoFile); parts.add(MultipartBody.Part.createFormData("any_name_for_the_part",videoFile.getName(), requestVideoFile)); } |
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.