Search code examples
androidfileuploadretrofitinternal-storage

How to upload images from internal storage to server using Retrofit?


I'm trying to upload two images from internal storage of my android device to HTTP-server.

    public interface ApiService {
        ...

        @Multipart
        @Headers("Content-Type: application/json")
        @POST("signature/{id}")
        Call<String> sendSignature(
                @Header("Authorization") String authorization,
                @Path("id") String id,
                @Part("descrtipion") RequestBody description,
                @Part MultipartBody.Part file1,
                @Part MultipartBody.Part file2);
    }

...


private void sendSignatures(){
    RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, getString(R.string.str_file_description));

    File file2 = getFileStreamPath(SIGNATURE2_PATH);
    RequestBody requestFile2 = RequestBody.create(MediaType.parse("image/png"), file2);
    MultipartBody.Part body2 = MultipartBody.Part.createFormData("sign1", file2.getName(), requestFile2);

    File file = getFileStreamPath(SIGNATURE_PATH);
    RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("sign2", file.getName(), requestFile);

    Call<String> call = ApiFactory.getService().sendSignature(token, PARAMETER_ID, description, body2, body);
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            if (response.isSuccessful()) Log.d("myLogs", "Yes: " + response.body());
            else Toast.makeText(MainActivity.this, ErrorUtils.errorMessage(response), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_LONG).show();
        }
    });
}

But server returns error #500. At the same time request from Postman is successful (#200).

Please, help me to fix it: where do I make a mistake in java-code?


Solution

  • I have found the solution. Particularly in this case it was necessary to remove header:

    public interface ApiService {
        ...
    
        @Multipart
        @POST("signature/{id}")
        Call<String> sendSignature(
                @Header("Authorization") String authorization,
                @Path("id") String id,
                @Part("descrtipion") RequestBody description,
                @Part MultipartBody.Part file1,
                @Part MultipartBody.Part file2);
    }
    

    When I tried to send this request through Postman and put only one file, or two files, one or both with wrong keys, even if token was incorrect, server passed #500 error. So first of all they check keys and files, and then - authorization parameter. I removed header and in this case got successful responce.