Uploading a file via Multipart
suggest changeDeclare your interface with Retrofit2 annotations:
public interface BackendApiClient { @Multipart @POST("/uploadFile") Call<RestApiDefaultResponse> uploadPhoto(@Part("file\"; filename=\"photo.jpg\" ") RequestBody photo); }
Where RestApiDefaultResponse
is a custom class containing the response.
Building the implementation of your API and enqueue the call:
Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl("http://<yourhost>/") .client(okHttpClient) .build(); BackendApiClient apiClient = retrofit.create(BackendApiClient.class); RequestBody reqBody = RequestBody.create(MediaType.parse("image/jpeg"), photoFile); Call<RestApiDefaultResponse> call = apiClient.uploadPhoto(reqBody); call.enqueue(<your callback function>);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents