How to POST Multipart Form Data using Android Retrofit

In this android programming source code example, we are going to POST Multipart Form Data using Android Retrofit.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to POST Multipart Form Data using Android Retrofit.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="15dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image"
        android:layout_centerInParent="true"/>

    <Button
        android:id="@+id/upload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        android:layout_alignParentBottom="true"
        android:text="Upload"/>

</RelativeLayout>

MainActivity.java

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.annotations.SerializedName;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public class RetrofitActivity7 extends AppCompatActivity {
    private Button upload;
    private ProgressDialog progressDialog;
    private String baseUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit7);
        upload = (Button) findViewById(R.id.upload);
        //eg baseUrl = "http://192.168.45.67/test/";
        baseUrl = "http://your-ip-address/test/";

        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitData();
            }
        });
    }

    private void submitData(){
        progressDialog = new ProgressDialog(RetrofitActivity7.this);
        progressDialog.setMessage(getString(R.string.loading));
        progressDialog.setCancelable(false);
        progressDialog.show();
        //Defining retrofit api service
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        File file = new File(Environment.getExternalStorageDirectory()+"/image.png");
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part fileupload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

        ApiService service = retrofit.create(ApiService.class);
        Call<PostResponse> call = service.postData(fileupload, filename);
        //calling the api
        call.enqueue(new Callback<PostResponse>() {
            @Override
            public void onResponse(Call<PostResponse> call, Response<PostResponse> response) {
                //hiding progress dialog
                progressDialog.dismiss();
                if(response.isSuccessful()){
                    Toast.makeText(getApplicationContext(), response.body().getSuccess(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<PostResponse> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    private interface ApiService {
        @Multipart
        @POST("index.php")
        Call<PostResponse> postData(
                @Part MultipartBody.Part file, @Part("name") RequestBody name);
    }

    private class PostResponse{
        @SerializedName("success")
        private String success;

        public void setSuccess(String success){
            this.success = success;
        }
        public String getSuccess(){
            return success;
        }
    }
}

index.php

run this script on yor localhost.

<?php

if (isset($_FILES['file']['name'])) {
  
$result = array("success" => $_FILES["file"]["name"]);
$file_path = basename($_FILES["file"]["name"]);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $file_path)){
  $result = array("success" => "File Upload");
}else{
  $result = array("success" => "Failed");
}
  }else {
    // File parameter is missing
    $result = array("success" => "No File received");
  }
  echo json_encode($result,JSON_PRETTY_PRINT);

?>

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment