Thursday, 23 March 2017

android Retrofit, Retro client multipart File upload with progress bar

android Retrofit, Retroclient multipart image File upload
android Retrofit, Retroclient multipart video File upload
android Retrofit, Retroclient multipart large image video File upload
android Retrofit, Retroclient multipart File upload with progress bar



public  void uploadFileToServer() {
            ApiInterface api =
                    ApiClient.getClient().create(ApiInterface.class);
            MultipartBody.Part body = prepareFilePart("image", selectedImageUri,new File(selectedPath));
            Call<ResponseBody> resultCall = api.uploadFile(body);
            resultCall.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call,
                                       Response<ResponseBody> response) {
                    Log.v("Upload", "success");
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.e("Upload error:", t.getMessage());
                }
            });
    }
    
    @NonNull
    private MultipartBody.Part prepareFilePart(String partName, Uri fileUri,File file) {
        RequestBody requestFile =
                RequestBody.create(
                        MediaType.parse(getContentResolver().getType(fileUri)),
                        file
                );
        return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
    }
Interface ApiInterface.java

public interface ApiInterface {

@Multipart
        @POST("uploadfile.php")
        Call<ResponseBody> uploadFile(
        @Part MultipartBody.Part file);
}

Class ApiClient.java
public class ApiClient {

    private static final String BASE_URL = "Your Post File url";
    private static Retrofit retrofit = null;


    static OkHttpClient client = new OkHttpClient.Builder()
            .followRedirects(true)
            .connectTimeout(0, TimeUnit.MILLISECONDS)
            .readTimeout(0, TimeUnit.MILLISECONDS)
            .build();

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                 .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}





android Retrofit, Retroclient multipart image File upload
android Retrofit, Retroclient multipart video File upload
android Retrofit, Retroclient multipart large image video File upload
android Retrofit, Retroclient multipart File upload with progress bar