Home » Android » java – Uploading compress image to server using retrofit

java – Uploading compress image to server using retrofit

Posted by: admin June 16, 2020 Leave a comment

Questions:

I am using retrofit in my project. Now I need to upload an image on server using retrofit. So I need help in the following question:

How to upload compressed bitmap to a server using retrofit in form data?
Any link or example will be helpful.

How to&Answers:

Upload can be done using below steps

Step 1: Create a method with below code

UploadPhotoRetroService service = ServiceGenerator.createService(MyActivity.class, "base-url");
TypedFile typedFile = new TypedFile("image/jpeg", new File(imagePath));
service.upload(typedFile, new Callback<String>() {
    @Override
    public void success(String result, Response response) {
        // success call back    
    }
    @Override
    public void failure(RetrofitError error) {
        error.printStackTrace();
    }
});

Step 2: Create Interface as below

public interface UploadPhotoRetroService {
    @Multipart
    @POST("/whatever-your-api")
    void upload(@Part("Photo") TypedFile file, Callback<String> callback);
}

Step 3: Create class as below

public class ServiceGenerator {

    private ServiceGenerator() {
    }

    public static <S> S createService(Class<S> serviceClass, String baseUrl) {
        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(baseUrl)
                .setClient(new OkClient(new OkHttpClient()));

        RestAdapter adapter = builder.build();

        return adapter.create(serviceClass);
    }
}