0

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

Ahmed Elsayed
  • 231
  • 3
  • 23

2 Answers2

1

Here is how I upload PNG images to my Server with Retrofit

val file = File(fileUri.path)
        val requestBody = RequestBody.create("image/*".toMediaTypeOrNull(), file)
        val fileToUpload = MultipartBody.Part.createFormData("image", file.name, requestBody)
        val filename = RequestBody.create("text/plain".toMediaTypeOrNull(), file.name)
webServiceApi.uploadFile(filename, fileToUpload)

Hope this can help you

MrVasilev
  • 1,503
  • 2
  • 17
  • 34
1

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());
Ahmed Elsayed
  • 231
  • 3
  • 23