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();
-
-
- 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 {
-
- @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() {
-
- File file = new File(mediaPath);
-
-
- 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.