How to upload an image file using retrofit2?

I am trying to upload an image from android device to server using Retrofit2 and end up getting error '400 Bad Request'. Below is the implementation. Could somebody help to fix the error?

Service :

@Multipart
@Headers("Content-type:application/json")
@POST("upload/profile")
Call<JsonObject> changePhotoProfile(@Part MultipartBody.Part partFile);

Here is my code :

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == 100) {
        if (data != null) {
            Uri uri = data.getData();
            uploadImageToServer(uri);
        }
    }
}

private void uploadImageToServer(Uri uri) {
    MultipartBody.Part partMap = prepareFilePart("file", uri);
    Call<JsonObject> changeImage = baseServiceAPI.changePhotoProfile(partMap);
    changeImage.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            
        }
    });
}

private MultipartBody.Part prepareFilePart(String partName, Uri uri) {
    File file = FileUtils.getFile(ProfileActivity.this, uri);
    RequestBody requestBody = RequestBody.create(MediaType.parse(Objects.requireNonNull(getContentResolver().getType(uri))), file);

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

1

Upvotes: 0

Views: 80

Answers (1)

Jyotish Biswas
Jyotish Biswas

Reputation: 574

You can try it without @Headers("Content-type:application/json")

like

@Multipart
@POST("upload/profile")
Call<JsonObject> changePhotoProfile(@Part MultipartBody.Part partFile);

it should work

Upvotes: 1

Related Questions