Uploading compress image to server using retrofit
Asked Answered
S

1

8

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.

Sanders answered 12/6, 2015 at 19:30 Comment(0)
D
8

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);
    }
}
Dish answered 15/6, 2015 at 11:58 Comment(3)
TypedFile is no longer available in Retrofit. Do you know how to do it without TypedFilePaintbox
Strange!! I am using TypedFile in my application to upload photo with Retrofit version 1.9.0 and it's working fine.Dish
For Retrofit 2.0 instead of TypedFile, you would create a ResponseBody using ResponseBody.createCorrugation

© 2022 - 2024 — McMap. All rights reserved.