title: How to upload an image file using retrofit2?
body: <p>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?</p>
  <p>Service :</p>
  <pre><code>@Multipart
  @Headers(&quot;Content-type:application/json&quot;)
  @POST(&quot;upload/profile&quot;)
  Call&lt;JsonObject&gt; changePhotoProfile(@Part MultipartBody.Part partFile);
  </code></pre>
  <p>Here is my code :</p>
  <pre><code>@Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (resultCode == RESULT_OK &amp;&amp; requestCode == 100) {
          if (data != null) {
              Uri uri = data.getData();
              uploadImageToServer(uri);
          }
      }
  }
  
  private void uploadImageToServer(Uri uri) {
      MultipartBody.Part partMap = prepareFilePart(&quot;file&quot;, uri);
      Call&lt;JsonObject&gt; changeImage = baseServiceAPI.changePhotoProfile(partMap);
      changeImage.enqueue(new Callback&lt;JsonObject&gt;() {
          @Override
          public void onResponse(Call&lt;JsonObject&gt; call, Response&lt;JsonObject&gt; response) {
              
          }
  
          @Override
          public void onFailure(Call&lt;JsonObject&gt; 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);
  }
  </code></pre>
  <p><img src="https://i.stack.imgur.com/RXHzh.png" alt="1" /></p>