Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Image Upload using Retrofit

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 5.01k
    Comment on it

    We are assuming you are already familiar with Retrofit. If not then first go to this. We have used multipart request for uploading image on server using Retrofit.

    Following are the simple and easy steps for image uploading using Retrofit:-

    Step 1: Add required dependency in your module level gradle file for using Retrofit

    compile 'com.squareup.retrofit2:retrofit:2.0.2'

    If you want to use GSON then add this dependency also

    compile 'com.squareup.retrofit2:converter-gson:2.0.2'

     

    Step 2: Create an interface that contain an abstract method with return type Call<ResponseBody>. In this example I am using two parameters in this method. You can change the number of parameter according to your requirement.

    public interface PicUploadInterface {
        @Multipart
        @POST("test.php")
        Call<ResponseBody> upload(@Part("description") RequestBody description,
                                  @Part MultipartBody.Part file);
    }

     

    Step 3: Create a class that contains following:-

    • Base url of your server
    • Instance of OkHttpClient.Builder
    • Instance of Retrofit.Builder
    public class ServiceGenerator {
    
        public static final String API_BASE_URL = "Your_Server_URL";
    
        private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    
        private static Retrofit.Builder builder =
                new Retrofit.Builder()
                        .baseUrl(API_BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create());
    
        public static <S> S createService(Class<S> serviceClass) {
            Retrofit retrofit = builder.client(httpClient.build()).build();
            return retrofit.create(serviceClass);
        }
    }

     

    Step 4: Now create an api manager class from where you will create a request, Inside your class create a method with whatever name you want (in my case it is uploadFile) do the following : 

    • Create reference of the interface created in previous step.
    • Create request body with media type multipart.
    • Crate body for multipart request.
    • Create Request body.
    • Crate the instance of the call and 
    public void uploadFile(File file) {
            // create upload service client
            PicUploadInterface service =
                    ServiceGenerator.createService(PicUploadInterface.class);
    
            // use the FileUtils to get the actual file by uri
            //File file = FileUtils.getFile(this, fileUri);
    
            // create RequestBody instance from file
            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("multipart/form-data"), file);
    
            // MultipartBody.Part is used to send also the actual file name
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("profilePicture", file.getName(), requestFile);
    
            // add another part within the multipart request
            String descriptionString = "hello, description goes here";
            RequestBody description =
                    RequestBody.create(
                            MediaType.parse("multipart/form-data"), "");
    
            // finally, execute the request
            Call<ResponseBody> call = service.upload(description, body);
            call.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());
                }
            });
        }

     

    Step 5: Call uploadFile method  of APIManager(It is singleton class which contains uploadFile method mentioned in step 4) in order upload image file and pass image file that has to be uploaded

    ApiManager.getInstance().uploadFile(file);

      For queries, do let me know in comments.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: