Rakesh P.
Rakesh P.

Reputation: 183

Retrofit Post Request With Form data

I am new to android . I want to upload image as form data using Retrofit Post method. I am using com.squareup.retrofit2:retrofit:2.3.0

enter image description here

This is my request body.

Upvotes: 1

Views: 11383

Answers (3)

Rakesh P.
Rakesh P.

Reputation: 183

I got output by doing request as following

UploadAPI Interface

`

@Multipart
@Headers({"TOKEN:XXXX"})
@POST("/api/messages/image")Call<ImageResult>uploadImage(@Part("sender_id")RequestBody sender_id,@Part("receiver_id")RequestBody receiver_id,@Part("type")RequestBody type,@Part MultipartBody.Part image);`

And Following is Method Code, I tried

`
private void uploadToServer(String filePath) 
{
  Retrofit retrofit = NetworkClient.getRetrofitClient(this, sendImageMsgURL);
  UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
  File file = new File(filePath);       
  MultipartBody.Part requestImage = null;
  RequestBody requestFile = RequestBody.create(MediaType.parse("mutlipart/form- 
  data"),file);
  requestImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
  RequestBody sender_id = RequestBody.create(MediaType.parse("multipart/form-data"), 
  currentID);
  RequestBody receiver_id = RequestBody.create(MediaType.parse("multipart/form-data"), 
  otherID);
  RequestBody type = RequestBody.create(MediaType.parse("multipart/form-data"), "image");
  Call<ImageResult> call = uploadAPIs.uploadImage(sender_id, receiver_id, type, 
  requestImage);
  call.enqueue(new Callback<ImageResult>() 
  {
     private Call<ImageResult> call;
     private Response<ImageResult> response;
     @Override
     public void onResponse(Call<ImageResult> call, Response<ImageResult> response)
     {
         this.call = call;
         this.response = response;
     }
     @Override
     public void onFailure(Call call, Throwable t) {
                Log.d("Error--------- :", t.getMessage());
            }
        });
    }`

Upvotes: 0

Dharmeet Soni
Dharmeet Soni

Reputation: 200

**Make interface like this add "MultipartBody.Part" in request and set your image path as post method and you can upload image using retrofit use this networkclient class to create retrofit instance **

public class NetworkClient {
    private static final String BASE_URL = "";
    private static Retrofit retrofit;
    public static Retrofit getRetrofitClient(Context context) {
        if (retrofit == null) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}

public interface UploadAPIs {
        @Multipart
        @POST("/upload")
        Call<ResponseBody> uploadImage(@Part MultipartBody.Part file, @Part("name") RequestBody requestBody);
    }    



     private void uploadToServer(String filePath) {
                 Retrofit retrofit = NetworkClient.getRetrofitClient(this);
                 UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
                 //Create a file object using file path
                 File file = new File(filePath);
                 // Create a request body with file and image media type
                 RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
                 // Create MultipartBody.Part using file request-body,file name and part name 
                 MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);
                 //Create request body with text description and text media type
                 RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");
                 // 
                 Call call = uploadAPIs.uploadImage(part, description);
                 call.enqueue(new Callback() {
                     @Override
                     public void onResponse(Call call, Response response) {
                     }
                     @Override
                     public void onFailure(Call call, Throwable t) {
                     }
                 });
             }

Upvotes: 2

Arpit bandil
Arpit bandil

Reputation: 204

Try this

    @Multipart
    @POST(Global.updateProfilePicture)
    Call<YOUR_RESPONSE_MODEL> updatePicture(@Header("Authorization") String authorization, @PartMap Map<String, RequestBody> params);

And API call should be like this

public void updatePic(String senderID, String receiverID, String type, File photo) {
    mProgressDialog.show();
    final Map<String, RequestBody> map = new HashMap<>();
    try {
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), photo);
        map.put("image\"; filename=\"" + photo.getName() + "\"", fileBody);
    } catch (Exception e) {
        e.printStackTrace();
    }
    map.put("sender_id", RequestBody.create(MediaType.parse("multipart/form-data"), senderID));
    map.put("receiver_id", RequestBody.create(MediaType.parse("multipart/form-data"), receiverID));
    map.put("type", RequestBody.create(MediaType.parse("multipart/form-data"), type));

    Call<YOUR_RESPONSE_MODEL> call = mApiInterface.updatePicture(ACCESS_TOKEN, map);
   call.enqueue(new Callback<YOUR_RESPONSE_MODEL>() {
            @Override
            public void onResponse(@NonNull Call<YOUR_RESPONSE_MODEL> call, @NonNull Response<YOUR_RESPONSE_MODEL> response) {
                if (mContext != null) {
                    mProgressDialog.dismiss();
                    // Dismiss Dialog
                   }
            }

            @Override
            public void onFailure(@NonNull Call<YOUR_RESPONSE_MODEL> call, @NonNull Throwable t) {
                if (mContext != null) {
                    mProgressDialog.dismiss();
                }
            }
        });
    }

Upvotes: 0

Related Questions