use this
Retrofit retrofit = new Retrofit.Builder().client(okHttpClient).baseUrl(domain)
.addConverterFactory(GsonConverterFactory.create()).build();
Service service = retrofit.create(Service.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
final MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
final RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
Call<ServerResponse> upload = service.uploadFile(fileToUpload, filename);
upload.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, final Response<ServerResponse> response) {
final ServerResponse serverResponse = response.body();
if (serverResponse.getSuccess()) {
//Handle Response
}
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
if(t instanceof SocketTimeoutException){
Toast.makeText(getApplicationContext(), "Unable To Upload\nError: Socket Time out. Please try again", Toast.LENGTH_LONG).show();
}
t.printStackTrace();
}
});
Service Interface
public interface Service {
@Multipart
@POST("path/upload.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);
}
2
solved How to make images upload faster in an Android app?