Upload Files To Server Using Retrofit 2 In Android

Upload Files To Server Using Retrofit 2 In Android
 

Introduction

 
In this article, we will learn how to upload any file to an online server using Retrofit 2 in Android.
 

Retrofit

 
Retrofit is an awesome HTTP library that improves the speed of server calls better than other HTTP libraries like Volley and Fast Android Networking. It depends on OKHTTP. To know more about the Retrofit visit here.
 
I have used PHP as my backend to receive the uploaded files from the Android App to the server. The coding part is split into two as server-side & client-side.
 
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 as PHP and paste the following lines.
    1. <?php  
    2. $target_dir = "uploads/";  
    3. $target_file_name = $target_dir .basename($_FILES["file"]["name"]);  
    4. $response = array();  
    5.   
    6. // Check if image file is an actual image or fake image  
    7. if (isset($_FILES["file"]))   
    8. {  
    9.    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))   
    10.    {  
    11.      $success = true;  
    12.      $message = "Successfully Uploaded";  
    13.    }  
    14.    else   
    15.    {  
    16.       $success = false;  
    17.       $message = "Error while uploading";  
    18.    }  
    19. }  
    20. else   
    21. {  
    22.       $success = false;  
    23.       $message = "Required Field Missing";  
    24. }  
    25. $response["success"] = $success;  
    26. $response["message"] = $message;  
    27. echo json_encode($response);  
    28.   
    29. ?>  
  1. I have created a folder named “uploads” to maintain uploaded files.
Client-Side
 
I have split this part into 3 steps as in the following.
  • 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 a new project.
  2. Name the project as your wish and select your activity template.
     
    Upload Files To Server Using Retrofit 2 In Android
     
  3. Click theFinish button to create a 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-app level build.gradle file to apply Google services to your project. 
    1. dependencies {  
    2. ...  
    3.    implementation 'com.squareup.retrofit2:retrofit:2.0.0'  
    4.    implementation 'com.squareup.retrofit2:converter-gson:2.0.0'  
    5. }  
  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()  
    5.                 .baseUrl(AppConfig.BASE_URL)  
    6.                 .addConverterFactory(GsonConverterFactory.create())  
    7.                 .build();  
    8.     }  
    9. }  
  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. }  
  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 parsing the server response and their name & type should be the 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 the file.
    1. private void uploadFile() {  
    2.     // Map is used to multipart the file using okhttp3.RequestBody      
    3.     File file = new File(mediaPath);  
    4.   
    5.     // Parsing any Media type file      
    6. RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);  
    7.     MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);  
    8.     RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());  
    9.   
    10.     ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);  
    11.     Call call = getResponse.uploadFile(fileToUpload, filename);  
    12.     call.enqueue(new Callback() {  
    13.     @Override          
    14.     public void onResponse(Call call, Response response) {  
    15.             ServerResponse serverResponse = response.body();  
    16.             if (serverResponse != null) {  
    17.                 if (serverResponse.getSuccess()) {  
    18.                     Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();  
    19.                 } else {  
    20.                     Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();  
    21.                 }  
    22.             } else {  
    23.                 assert serverResponse != null;  
    24.                 Log.v("Response", serverResponse.toString());  
    25.             }  
    26.             progressDialog.dismiss();  
    27.         }  
    28.   
    29.         @Override          
    30.         public void onFailure(Call call, Throwable t) {  
    31.   
    32.         }  
    33.     });  
    34. }  
  • Here, Map is used to multipart the file using okhttp3.RequestBody.
  • RequestBody is created with the selected file & MultipartBody. A part with file RequestBody.
  • We can pass media files with a normal server call also.
In this part, we have learned how to upload a single file using Retrofit 2. IN the next part we will learn 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. 

Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles