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
- 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 PHP and paste the following lines.
- <?php
- $target_dir = "uploads/";
- $target_file_name1 = $target_dir .basename($_FILES["file1"]["name"]);
- $target_file_name2 = $target_dir .basename($_FILES["file2"]["name"]);
- $response = array();
-
- if (isset($_FILES["file1"]) && isset($_FILES["file2"]))
- {
- if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file_name1)
- && move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file_name2))
- {
- $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
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
- Open Android Studio and Select "Create New Project".
- Name the project as your wish and select your activity template.
- 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.
- Then add the following lines in the 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);
- @Multipart
- @POST("retrofit_example/upload_multiple_files.php")
- Call < ServerResponse > uploadMulFile(@Part MultipartBody.Part file1, @Part MultipartBody.Part file2);
- }
- 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 parse the server response and their name & type should be 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 multiple files to the server.
-
- private void uploadMultipleFiles() {
- progressDialog.show();
-
- File file = new File(mediaPath);
- File file1 = new File(mediaPath1);
-
- RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
- RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);
- MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
- MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);
- ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
- Call < ServerResponse > call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
- call.enqueue(new Callback < ServerResponse > () {
- @Override
- public void onResponse(Call < ServerResponse > call, Response < ServerResponse > 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 < ServerResponse > call, Throwable t) {}
- });
- }
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.