Search code examples
androidfilemultipart

Files appear corrupted on server using Multipart with Retrofit2


This is the first time I use Multipart . I'm trying to upload files either images or pdfs in my server

File Uploaded to server but in every time this file is corrupted . File Path Like content:/com.android.providers.media.documents/document/image%3A5122.jpg

I use Retrofit 2 and here is my code

API Service

 @Multipart
@POST("Attachment")
Call<Boolean> PostAttachments(@Query("user_id") int userID,
                              @Query("main_id") int mainID,
                              @Query("service_id") int serviceID,
                              @Query("is_car")Boolean isCar,
                              @Part MultipartBody.Part file);

And here is I use Multipart

 @Override
public void postAttachment(OnFinishedListner onFinishedListner,int userID,int mainID,int serviceID,Boolean isCar,File file) {
    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file.getPath());
    MultipartBody.Part multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);
    APIService apiService = APIClient.getInstanceRetrofit().create(APIService.class);
    Call<Boolean> call = apiService.PostAttachments(userID,mainID,serviceID,isCar,multipartBody);
    call.enqueue(new Callback<Boolean>() {
        @Override
        public void onResponse(Call<Boolean> call, Response<Boolean> response) {
            onFinishedListner.onFinished(response.body());
        }

        @Override
        public void onFailure(Call<Boolean> call, Throwable t) {
            onFinishedListner.onFailed(t);
        }
    });

}

File path posted successfully in database and the file appears in my server and its extention like .jpg but when I open it , it appear corrupted


Solution

  • I solved my problem by replacing the RequestBody

    Replacing

    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file.getPath());
    

    with

    RequestBody requestFile = RequestBody.create(MediaType.parse("*/*"), file.getAbsoluteFile());