
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
- To use PHP, you need PhpMyAdmin (with WAMP or XMPP) server.
- Then open your hosting path (For WAMP – C:\Wamp\www).
- Create a PHP file named as PHP and paste the following lines.
- <?php
- $target_dir = "uploads/";
- $target_file_name = $target_dir .basename($_FILES["file"]["name"]);
- $response = array();
- // Check if image file is an actual image or fake image
- if (isset($_FILES["file"]))
- {
- if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
- {
- $success = true;
- $message = "Successfully Uploaded";
- }
- else
- {
- $success = false;
- $message = "Error while uploading";
- }
- }
- else
- {
- $success = false;
- $message = "Required Field Missing";
- }
- $response["success"] = $success;
- $response["message"] = $message;
- echo json_encode($response);
- ?>
- 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
- Open Android Studio and Select Create a new project.
- Name the project as your wish and select your activity template.

- Click the “Finish” 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.
- Then add the following lines in-app level build.gradle file to apply Google services to your project.
- dependencies {
- ...
- implementation 'com.squareup.retrofit2:retrofit:2.0.0'
- implementation 'com.squareup.retrofit2:converter-gson:2.0.0'
- }
- Then click “Sync Now” to setup your project.
- Don't forget to add the following permission in your manifest file.
- <uses-permission android:name="android.permission.INTERNET"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step 3 - Implementation of File Uploader using Retrofit 2
- Create a class file named as “AppConfig.java” and add the following lines.
- class AppConfig {
- private static String BASE_URL = "base_address";
- static Retrofit getRetrofit() {
- return new Retrofit.Builder()
- .baseUrl(AppConfig.BASE_URL)
- .addConverterFactory(GsonConverterFactory.create())
- .build();
- }
- }
- Create an interface file named as “ApiConfig.java” and add the following lines.
- interface ApiConfig {
- @Multipart
- @POST("retrofit_example/upload_image.php")
- Call uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);
- }
- Create a model class named as “ServerResponse.java” and add the following lines
- class ServerResponse {
- // variable name should be same as in the json response from php
- @SerializedName("success")
- boolean success;
- @SerializedName("message")
- String message;
- String getMessage() {
- return message;
- }
- boolean getSuccess() {
- return success;
- }
- }
- 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.
- The files are uploaded using MultipartBody of OkHttp3. The following code snippet is used to upload the file.
- private void uploadFile() {
- // Map is used to multipart the file using okhttp3.RequestBody
- File file = new File(mediaPath);
- // Parsing any Media type file
- RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
- MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
- RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
- ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
- Call call = getResponse.uploadFile(fileToUpload, filename);
- call.enqueue(new Callback() {
- @Override
- public void onResponse(Call call, Response response) {
- ServerResponse serverResponse = response.body();
- if (serverResponse != null) {
- if (serverResponse.getSuccess()) {
- Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
- }
- } else {
- assert serverResponse != null;
- Log.v("Response", serverResponse.toString());
- }
- progressDialog.dismiss();
- }
- @Override
- public void onFailure(Call call, Throwable t) {
- }
- });
- }
- 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.

Akshay JainPosted Sep 18, 2019, 10:07 AM
Hello, I work with asp.net Web services (.asmx) C# but this android code doesn't work to upload the image from android to asp.net. Will you please help to solve the problem and problem you can find from here: https://stackoverflow.com/q/57909118/10325004
Eloy Muñoz MarinPosted Jun 30, 2019, 12:59 PM
Hello. I have a little app, both login and register works well using retrofit and @GET but when I try to use @POST for uploading a file... The code I have is almost the same than above but its like it does not "watch" the php file for upload. It goes to onFailure directly, no crashes, I have no idea what the problem can be cause with @GET works and @POST not working. Tried the register and login with @POST and did not worked neither. Edit: the file is uploaded but still it goes to onFailure instead of onResponse on call.enqueue...
harini danduPosted Jun 22, 2019, 3:19 PM
Sir, app is crashing while uploading the file. I am using XMPP server and placed php file in the main directory of XMPP. What is the error? Please help me out!
natasha chaudharyPosted Jun 12, 2019, 12:53 PM
Sir I've followed the exact same procedure as you did but my file is not getting uploaded anywhere. I'm using wamp server and have placed the php file in www folder in a directory named uploads. Is there anything that I'm missing? Pls help me out. Thank you!
Nguyễn Đình TháiPosted May 21, 2019, 11:22 PM
What's your host contain