用Retrofit+Rxjava上传图片支持多张图片的上传

1.这是一个接口

    @POST
    Observable Image(@Url String url, @HeaderMap Map headermap,@Body MultipartBody body);

第一个是上传一个 第二个是上传多个

下面这个是一个Retrofit 封装好的工具类

public class Retrofits{
    private MyApiService myApiService;

    public Retrofits() {
        HttpLoggingInterceptor loggingInterceptor =new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient =new OkHttpClient.Builder()
                .readTimeout(20,TimeUnit.SECONDS)
                .connectTimeout(20,TimeUnit.SECONDS)
                .writeTimeout(20,TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .retryOnConnectionFailure(true)
                .build();
        Retrofit retrofit =new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//                存放的头文件
                .baseUrl(Contacts.BASE_URL)
                .client(okHttpClient)
                .build();
        myApiService =retrofit.create(MyApiService.class);
    }

    public static  Retrofits getInstance(){
        return RetroHolder.OK_UTIL;
    }

    static class RetroHolder{
        private static final Retrofits OK_UTIL =new Retrofits ();
    }
    /**
     * 封装一个上传图片
     */
    public OkUtil image(String murl,Map headermap,Map map,List list){
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (list.size()==1) {
            for (int i = 0; i < list.size(); i++) {
                File file = new File((String) list.get(i));
                builder.addFormDataPart("image", file.getName(),RequestBody.create(MediaType.parse("multipart/octet-stream"),file));
            }
        }
        myApiService.Image(murl,headermap,builder.build())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        return Retrofits.getInstance();
    }
    /**
     * 多个图片的上传
     */
    public OkUtil pinglun(String murl,Map headermap,Map map,List list){
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("commodityId",String.valueOf(map.get("commodityId")));
        if(!String.valueOf(map.get("orderId")).equals("")){
        builder.addFormDataPart("orderId",String.valueOf(map.get("orderId")));
    }
        builder.addFormDataPart("content",String.valueOf(map.get("content")));
        if (list.size()!=0) {
        for (int i = 1; i < list.size(); i++) {
            File file = new File((String) list.get(i));
            builder.addFormDataPart("image", file.getName(),RequestBody.create(MediaType.parse("multipart/octet-stream"),file));
        }
    }
        myApiService.Image(murl,headermap,builder.build())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(observer);
        return Retrofits.getInstance();
}
//    重写一个观察者模式
    private Observer observer =new Observer(){
        @Override
        public void onCompleted() {
        }
        @Override
        public void onError(Throwable e) {
            if(httpListener!=null){
                httpListener.onError(e.getMessage());
            }
        }
        @Override
        public void onNext(ResponseBody responseBody) {
            if(httpListener !=null){
                try {
                    httpListener.onSuccess(responseBody.string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };
    public interface HttpListener{
        void onSuccess(String gsonstr);
        void onError(String error);
    }
    private HttpListener httpListener;
    public void setHttpListener(HttpListener listener){
        this.httpListener =listener;
    }
}
 
  

一个方法把得到的图片路径 变为String类型

public String getFilePath(String fileName, int requestCode, Intent data) {
        if (requestCode == 1) {
            return fileName;
        } else if (requestCode == 0) {
            Uri uri = data.getData();
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            String img_path = actualimagecursor
                    .getString(actual_image_column_index);
            // 4.0以上平台会自动关闭cursor,所以加上版本判断,OK
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                actualimagecursor.close();
            return img_path;
        }
        return null;
    }

一个打开图库的方法

Intent intent1 = new Intent(Intent.ACTION_PICK);
                intent1.setType("image/*");
                startActivityForResult(intent1,0);

重写一个回调方法

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data==null){
            return;
        }
        if(requestCode==0){
            String filePath = getFilePath(null,requestCode,data);
            /**
             * 这里是用的一个图片的上传
             */
            Map map = new HashMap<>();
            List list =new ArrayList<>();
            list.add(filePath);
            pressent.image(Contacts.UploadYourHead, headermap, map,list,Register.class);
        }
    }
 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(安卓学习)