Junior — Middle
How can you send an image to the server using the Retrofit library?
sobes.tech AI
Answer from AI
To send an image to the server using Retrofit, a multipart request is usually used. The image is transmitted as part of a form with the type MultipartBody.Part. Example:
// API interface
public interface ApiService {
@Multipart
@POST("upload")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part image);
}
// Preparing the file and creating MultipartBody.Part
File file = new File("path/to/image.jpg");
RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// Calling the API
ApiService service = retrofit.create(ApiService.class);
Call<ResponseBody> call = service.uploadImage(body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
// handle successful response
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
// handle error
}
});
This approach allows you to send a file as part of a multipart/form-data request, which is often required for uploading images to a server.