Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading compress image to server using retrofit

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.

like image 597
Mahesh Avatar asked Jun 12 '15 19:06

Mahesh


1 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);
    }
}
like image 183
Shankar Prasad Avatar answered Oct 02 '22 23:10

Shankar Prasad