Using Post Retrofit to Upload File Android

  • Updated date Feb 19, 2020
  • 116.7k
  • half dozen

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

Upload Files To Server Using Retrofit 2 In Android

Introduction

In this article, we will larn 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 improve than other HTTP libraries like Volley and Fast Android Networking. It depends on OKHTTP. To know more about the Retrofit visit here.

I accept used PHP every bit my backend to receive the uploaded files from the Android App to the server. The coding function is split into two as server-side & client-side.

Coding Part,

Server Side

  1. To use PHP, yous need PhpMyAdmin (with WAMP or XMPP) server.
  2. Then open your hosting path (For WAMP – C:\Wamp\www).
  3. Create a PHP file named equally PHP and paste the post-obit lines.
    1. <?php
    2. $target_dir ="uploads/" ;
    3. $target_file_name = $target_dir .basename($_FILES["file" ][ "proper name" ]);
    4. $response = assortment();
    5. if  (isset($_FILES[ "file" ]))
    6. {
    7. if  (move_uploaded_file($_FILES[ "file" ][ "tmp_name" ], $target_file_name))
    8.    {
    9.      $success =true ;
    10.      $message ="Successfully Uploaded" ;
    11.    }
    12. else
    13.    {
    14.       $success =false ;
    15.       $message ="Error while uploading" ;
    16.    }
    17. }
    18. else
    19. {
    20.       $success =fake ;
    21.       $message ="Required Field Missing" ;
    22. }
    23. $response["success" ] = $success;
    24. $response["message" ] = $bulletin;
    25. echo json_encode($response);
    26. ?>
  1. I have created a folder named "uploads" to maintain uploaded files.

Customer-Side

I accept carve up this part into 3 steps as in the following.

  • Step 1 - Creating a New Project with Empty Activity.
  • Step ii - 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 projection.
  2. Proper noun the project as your wish and select your activeness template.

    Upload Files To Server Using Retrofit 2 In Android

  3. Click the " Stop " push to create a new project in Android Studio.

Pace 2 - Setting upwards the Retrofit Http Library and Manifest

In this function, we will see how to prepare the library for the project.

  1. Then add the following lines in-app level build.gradle file to use Google services to your project.
    1. dependencies {
    2. ...
    3.    implementation'com.squareup.retrofit2:retrofit:two.0.0'
    4.    implementation'com.squareup.retrofit2:converter-gson:two.0.0'
    5. }
  1. Then click "Sync At present" to setup your project.
  2. Don't forget to add the following permission in your manifest file.
    1. <uses-permission android:proper noun= "android.permission.Internet" />
    2. <uses-permission android:proper name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step iii - Implementation of File Uploader using Retrofit 2

  1. Create a grade file named as "AppConfig.coffee" and add the following lines.
    1. class  AppConfig {
    2. private static  Cord BASE_URL = "base_address" ;
    3. static  Retrofit getRetrofit() {
    4. render 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.     Phone call uploadFile(@Office MultipartBody.Part file, @Part("file" ) RequestBody proper name);
    5. }
  1. Create a model class named equally "ServerResponse.coffee" and add the following lines
    1. class  ServerResponse {
    2.     @SerializedName("success" )
    3. boolean  success;
    4.     @SerializedName("message" )
    5.     String bulletin;
    6.     Cord getMessage() {
    7. render  bulletin;
    8.     }
    9. boolean  getSuccess() {
    10. return  success;
    11.     }
    12. }
  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.     File file =new  File(mediaPath);
    3. RequestBody requestBody = RequestBody.create(MediaType.parse("*/*" ), file);
    4.     MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file" , file.getName(), requestBody);
    5.     RequestBody filename = RequestBody.create(MediaType.parse("text/manifestly" ), file.getName());
    6.     ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class );
    7.     Phone call call = getResponse.uploadFile(fileToUpload, filename);
    8.     call.enqueue(new  Callback() {
    9.     @Override
    10. public void  onResponse(Call call, Response response) {
    11.             ServerResponse serverResponse = response.body();
    12. if  (serverResponse != nada ) {
    13. if  (serverResponse.getSuccess()) {
    14.                     Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
    15.                 }else  {
    16.                     Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
    17.                 }
    18.             }else  {
    19.                 assert serverResponse !=aught ;
    20.                 Log.v("Response" , serverResponse.toString());
    21.             }
    22.             progressDialog.dismiss();
    23.         }
    24.         @Override
    25. public void  onFailure(Call phone call, Throwable t) {
    26.         }
    27.     });
    28. }
  • Hither, Map is used to multipart the file using okhttp3.RequestBody.
  • RequestBody is created with the selected file & MultipartBody. A office with file RequestBody.
  • Nosotros can pass media files with a normal server call also.

In this office, we have learned how to upload a single file using Retrofit 2. IN the adjacent role we will learn how to upload multiple files using Retrofit two.

Download Code

Yous tin download the full source code of the commodity in GitHub. If y'all like this article, practice star the repo in GitHub.

highsmithapereens.blogspot.com

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

0 Response to "Using Post Retrofit to Upload File Android"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel