Upload Video to Server in Android Using Multipart Example

  • Updated date Feb 19, 2020
  • 56k
  • 6

This article is a continuity of the article "Upload file to server using Retrofit 2 in Android", where we have learned how to upload file to server. In this article, we will learn how to upload many files to online 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. if  (isset($_FILES[ "file1" ]) && isset($_FILES[ "file2" ]))
    7.    {
    8.    if  (move_uploaded_file($_FILES[ "file1" ][ "tmp_name" ], $target_file_name1)
    9.    && move_uploaded_file($_FILES["file2" ][ "tmp_name" ], $target_file_name2))
    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. ?>
  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.     @SerializedName("success" )
    3. boolean  success;
    4.     @SerializedName("message" )
    5.     String message;
    6.     String getMessage() {
    7. return  message;
    8.     }
    9. boolean  getSuccess() {
    10. return  success;
    11.     }
    12. }
  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. private void  uploadMultipleFiles() {
    2.     progressDialog.show();
    3.     File file =new  File(mediaPath);
    4.     File file1 =new  File(mediaPath1);
    5.     RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*" ), file);
    6.     RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*" ), file1);
    7.     MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1" , file.getName(), requestBody1);
    8.     MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2" , file1.getName(), requestBody2);
    9.     ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class );
    10.     Call < ServerResponse > call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
    11.     call.enqueue(new  Callback < ServerResponse > () {
    12.         @Override
    13. public void  onResponse(Call < ServerResponse > call, Response < ServerResponse > response) {
    14.             ServerResponse serverResponse = response.body();
    15. if  (serverResponse != null ) {
    16. if  (serverResponse.getSuccess()) {
    17.                     Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
    18.                 }else  {
    19.                     Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
    20.                 }
    21.             }else  {
    22.                 assert serverResponse !=null ;
    23.                 Log.v("Response" , serverResponse.toString());
    24.             }
    25.             progressDialog.dismiss();
    26.         }
    27.         @Override
    28. public void  onFailure(Call < ServerResponse > call, Throwable t) {}
    29.     });
    30. }

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.

Upload Video to Server in Android Using Multipart Example

Source: https://www.c-sharpcorner.com/article/upload-multiple-files-to-server-using-retrofit-2-in-android/

0 Response to "Upload Video to Server in Android Using Multipart Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel