Uploading compress image to server using retrofit

半城伤御伤魂 提交于 2019-12-08 17:03:56

问题


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.


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/30810829/uploading-compress-image-to-server-using-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!