Upload Multiple Files To Server Using Retrofit 2 In Android

upload-multiple-files-to-server-using-retrofit

Introduction

 
This article is a continuation of the article Upload file to the server using Retrofit 2 in Android, where we have learned how to upload the file to a server. In this article, we will learn how to upload many files to an online server using Retrofit 2 in Android.
 
Coding Part
 
Server Side
  1. To use PHP, you need PhpMyAdmin (with WAMP or XMPP) server.
  2. Then open your hosting path (For WAMP – C:\Wamp\www).
  3. Create a PHP file named PHP and paste the following lines.
    1. <?php  
    2. $target_dir = "uploads/";  
    3. $target_file_name1 = $target_dir .basename($_FILES["file1"]["name"]);  
    4. $target_file_name2 = $target_dir .basename($_FILES["file2"]["name"]);  
    5. $response = array();  
    6. // Check if image file is an actual image or fake image  
    7. if (isset($_FILES["file1"]) && isset($_FILES["file2"]))  
    8.    {  
    9.    if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file_name1)  
    10.    && move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file_name2))  
    11.       {  
    12.          $success = true;  
    13.          $message = "Successfully Uploaded";  
    14.       }  
    15.    else  
    16.       {  
    17.          $success = false;  
    18.          $message = "Error while uploading";  
    19.       }  
    20.    }  
    21. else  
    22.    {  
    23.       $success = false;  
    24.       $message = "Required Field Missing";  
    25.    }  
    26.    $response["success"] = $success;  
    27.    $response["message"] = $message;  
    28.    echo json_encode($response);  
    29. ?>  
  1. I have created a folder named “uploads” to maintain uploaded files.
Client-Side
 
Follow the same steps as followed in the previous article. For your reference, I have detailed the steps as in the following. You can skip step 1 & 2, if you familiar with the previous article.
  • Step 1 - Creating a New Project with Empty Activity.
  • Step 2 - Setting up the Retrofit HTTP Library and Manifest.
  • Step 3 - Implementation of File uploader using Retrofit.
Step 1 - Creating a New Project with Android Studio
  1. Open Android Studio and Select "Create New Project".
  2. Name the project as your wish and select your activity template.
     
    Upload Multiple Files To Server Using Retrofit 2 In Android
     
  3. Click Finish button to create the new project in Android Studio.
Step 2 - Setting up the Retrofit Http Library and Manifest
 
In this part, we will see how to set up the library for the project.
  1. Then add the following lines in the app level build.gradle file to apply Google services to your project. 
    1. dependencies {   
    2.     ...implementation 'com.squareup.retrofit2:retrofit:2.0.0'  
    3.     implementation 'com.squareup.retrofit2:converter-gson:2.0.0'  
    4. }  
  1. Then click Sync Now to setup your project.
     
  2. Don't forget to add the following permission in your manifest file. 
    1. <uses-permission android:name="android.permission.INTERNET"/>  
    2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
Step 3 - Implementation of File Uploader using Retrofit 2
  1. Create a class file named as “AppConfig.java” and add the following lines. 
    1. class AppConfig {  
    2.     private static String BASE_URL = "base_address";  
    3.     static Retrofit getRetrofit() {  
    4.         return new Retrofit.Builder().baseUrl(AppConfig.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();  
    5.     }  
    6. }  
  1. Create an interface file named as “ApiConfig.java” and add the following lines.
    1. interface ApiConfig {  
    2.     @Multipart  
    3.     @POST("retrofit_example/upload_image.php")  
    4.     Call uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);  
    5.     @Multipart  
    6.     @POST("retrofit_example/upload_multiple_files.php")  
    7.     Call < ServerResponse > uploadMulFile(@Part MultipartBody.Part file1, @Part MultipartBody.Part file2);  
    8. }  
  1. Create a model class named as “ServerResponse.java” and add the following lines.
    1. class ServerResponse {  
    2.     // variable name should be same as in the json response from php  
    3.     @SerializedName("success")  
    4.     boolean success;  
    5.     @SerializedName("message")  
    6.     String message;  
    7.     String getMessage() {  
    8.         return message;  
    9.     }  
    10.     boolean getSuccess() {  
    11.         return success;  
    12.     }  
    13. }  
  1. The SerializedName annotation is used to parse the server response and their name & type should be same as the JSON Response received from the server.
      
  2. The files are uploaded using MultipartBody of OkHttp3. The following code snippet is used to upload multiple files to the server. 
    1. // Uploading Image/Video  
    2. private void uploadMultipleFiles() {  
    3.     progressDialog.show();  
    4.     // Map is used to multipart the file using okhttp3.RequestBody  
    5.     File file = new File(mediaPath);  
    6.     File file1 = new File(mediaPath1);  
    7.     // Parsing any Media type file  
    8.     RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);  
    9.     RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);  
    10.     MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);  
    11.     MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);  
    12.     ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);  
    13.     Call < ServerResponse > call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);  
    14.     call.enqueue(new Callback < ServerResponse > () {  
    15.         @Override  
    16.         public void onResponse(Call < ServerResponse > call, Response < ServerResponse > response) {  
    17.             ServerResponse serverResponse = response.body();  
    18.             if (serverResponse != null) {  
    19.                 if (serverResponse.getSuccess()) {  
    20.                     Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();  
    21.                 } else {  
    22.                     Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();  
    23.                 }  
    24.             } else {  
    25.                 assert serverResponse != null;  
    26.                 Log.v("Response", serverResponse.toString());  
    27.             }  
    28.             progressDialog.dismiss();  
    29.         }  
    30.         @Override  
    31.         public void onFailure(Call < ServerResponse > call, Throwable t) {}  
    32.     });  
    33. }  
Here, each file is converted to multipart body and sent to the server.
 
In this part, we have learned how to upload multiple files using Retrofit 2.
 
Download Code
 
You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. 


Similar Articles