Skip to content Skip to sidebar Skip to footer

Send Form Data To Server In Retrofit

Trying to send form data to the server via Retrofit but unable to request to the server. I want to post an image array with their data. val builder: MultipartBody.Builder = Multipa

Solution 1:

Dummy api interface.

publicinterfaceApiInterface {
        @Multipart@POST(URLHelper.register)
        Call<ModelProp> signUp2(@Part List<MultipartBody.Part> photos,
                          @PartMap Map<String, RequestBody> map;
    }

Now create data to post like this.

Map<String, RequestBody> partMap = new HashMap<>();
List<MultipartBody.Part> images = new ArrayList<>();
partMap.put("device_id", createPartFromString(deviceId)); // add data which are common for all images like device_id, device_token, device_type etc.
..
..

for (int i=0; i < upFileList.size(); i++){
   images.add(prepareFilePart("provider_documents["+i+"][document]", imageFile));
   partMap.add("provider_documents["+i+"][expires_at]", createPartFromString(expiry)); // add image specific data. 
 ...
 ..
}
...
..
observable = apiInterface.signUp2(images, partMap).

createPartFromString method

publicRequestBodycreatePartFromString(Stringstring) {
        returnRequestBody.create(MultipartBody.FORM, string);
}

prepareFilePart method

privateMultipartBody.PartprepareFilePart(String partName, File file){
    RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);

    returnMultipartBody.Part.createFormData(partName, file.getName(),requestBody);
}

Solution 2:

Use it Like this:-

// @Multipart@POST(URLHelper.register)
fun signUp2(@Partbuilder: MultipartBody ): Observable<Registration>

Updated :-

privatevoiduploadToServer(String filePath) {
        showProgressDialog();
        Retrofitretrofit= RetrofitClient.getRetrofitClient(this);
        ApiInterfaceuploadAPIs= retrofit.create(ApiInterface.class);
        Filefile=newFile(filePath);
        //compressor.setDestinationDirectoryPath()RequestBodyfileReqBody= RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Partpart= MultipartBody.Part.createFormData("fileUpload", file.getName(), fileReqBody);
        //RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");RequestBodyimgNameReqBody= RequestBody.create(MediaType.parse("multipart/form-data"), "B2B_" + System.nanoTime());

        uploadAPIs.uploadImage(imgNameReqBody, part).enqueue(newCallback<UploadImageRespose>() {
            @OverridepublicvoidonResponse(@NonNull Call<UploadImageRespose> call, @NonNull retrofit2.Response<UploadImageRespose> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getCODE().equalsIgnoreCase("SUCCESS")) {
                        Toast.makeText(Activity.this, "Profile Image Upload Succesfully", Toast.LENGTH_SHORT).show();
                    } else {
                        hideProgressDialog();
                        Toast.makeText(Activity.this, "Some Error  occurred, try again", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    hideProgressDialog();
                }

            }

            @OverridepublicvoidonFailure(@NonNull Call<UploadImageRespose> call, @NonNull Throwable t) {
                Timber.d(TAG, t.getMessage());
                hideProgressDialog();
                Toast.makeText(Activity.this, "Some Error  occurred, try again", Toast.LENGTH_SHORT).show();
            }
        });
    }

add below method in your interface:-

@Multipart@POST("Your Path Here")
    Call<UploadImageRespose> uploadImage(@Part("img_name") RequestBody img_name,
                                         @Part MultipartBody.Part file);

Post a Comment for "Send Form Data To Server In Retrofit"