retrofit+rxjava

Retrofit文件上传(MVP模式下)

2018-10-22  本文已影响106人  打酱油的日光灯

打造终极MVP+Retrofit2+okhttp3+Rxjava2网络请求,开发实用,简约,由于篇幅字数原因 本章讲解Retrofit文件上传

抓住人生中的一分一秒,胜过虚度中的一月一年!

前言

目前较火的网络请求其中有MVP+Retrofit2+okhttp3+Rxjava2,于是我也加入了使用行列,在网上找了许多案例,实际代码开发中解决了一些所谓的坑,总结了些内容与大家共享一下,有不足的地方希望大家提出我将进行再次完善。

实现目标

1、单图上传
2、多图上传
3、图片参数混合上传


先看下我自己封装的工具类,下边都会用到

/**
 * File descripition:   RetrofitUtil工具类
 *
 * @author lp
 * @date 2018/8/13
 */

public class RetrofitUtil {
    /**
     * 将String 字符串转换为Rrtorfit: requestBody类型的value
     */
    public static RequestBody convertToRequestBody(String param) {
        RequestBody requestBody = null;
        requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
        return requestBody;
    }

    /**
     * 将所有的File图片集合转化为retorfit上传图片所需的: MultipartBody.Part类型的集合
     */
    public static List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files, String key) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
            parts.add(filesToMultipartBodyParts(file, key));
        }
        return parts;
    }

    /**
     * 将单个File图片转化为retorfit上传图片所需的: MultipartBody.Part类型
     */
    public static MultipartBody.Part filesToMultipartBodyParts(File file, String key) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData(key, file.getName(), requestBody);
        return part;
    }

    public static List<File> initImages(List<String> mImages) {
        List<File> listPicture = new ArrayList<>();
        listPicture.clear();
        Iterator<String> stuIter = mImages.iterator();
        while (stuIter.hasNext()) {
            String mUrl = stuIter.next();
            listPicture.add(new File(mUrl));
        }
        return listPicture;
    }
}
1、单图上传

1.第一种方法
首先创建接口,注意注解需要用@Multipart 参数形式@Part MultipartBody.Part parts

@Multipart
@POST("api/Company/register")
Observable<BaseModel<Object>> upLoadImg(@Part MultipartBody.Part parts);

public interface UpLoadView extends BaseView {
    void onUpLoadImgSuccess(BaseModel<Object> o);
}

public class UpLoadPresenter extends BasePresenter<UpLoadView> {
    public UpLoadPresenter(UpLoadView baseView) {
        super(baseView);
    }

    public void upLoadImgApi(MultipartBody.Part parts) {
        addDisposable(apiServer.upLoadImg(parts), new BaseObserver(baseView) {
            @Override
            public void onSuccess(Object o) {
                baseView.onUpLoadImgSuccess((BaseModel<Object>) o);
            }

            @Override
            public void onError(String msg) {
                if (baseView != null) {
                    baseView.showError(msg);
                }
            }
        });
    }
}

 @Override
 public void onClick(View v) {
        /**
         * 俩个参数  一个是图片路径   一个是和后台约定的Key,如果后台不需要,随便写都行
         */
        mPresenter.upLoadImgApi(RetrofitUtil.filesToMultipartBodyParts(new File("tupian.lujing"), "tupian.key"));
    }

2.第二种方法
首先创建接口,注意注解需要用@Multipart 参数形式List<MultipartBody.Part> parts
问:为啥用List? 答:List只有一张图片不就是单张了 可以冷笑一下不介意

@Multipart
@POST("api/user_info/update_headimg")
Observable<BaseModel<Object>> upHeadImg(@Part List<MultipartBody.Part> parts);
public interface UpLoadView extends BaseView {
    void onUpHeadImgSuccess(BaseModel<Object> o);
}

public class UpLoadPresenter extends BasePresenter<UpLoadView> {
    public UpLoadPresenter(UpLoadView baseView) {
        super(baseView);
    }

    public void upHeadImgApi(List<MultipartBody.Part> parts) {
        addDisposable(apiServer.upHeadImg(parts), new BaseObserver(baseView) {
            @Override
            public void onSuccess(Object o) {
                baseView.onUpHeadImgSuccess((BaseModel<Object>) o);
            }

            @Override
            public void onError(String msg) {
                if (baseView != null) {
                    baseView.showError(msg);
                }
            }
        });
    }
}
@Override
public void onClick(View v) {
    /**
     * 俩个参数  一个是图片集合路径   一个是和后台约定的Key,如果后台不需要,随便写都行
     */
  List<String> strings=new ArrayList<>();
    for (int i=0;i<1;i++){
        strings.add("tupian.lujing");
    }
    mPresenter.upHeadImgApi(RetrofitUtil.filesToMultipartBodyParts(RetrofitUtil.initImages(strings), "tupian.key"));
}
1、多图上传

和单图上传第二种方法一样

@Multipart
@POST("api/user_info/update_headimg")
Observable<BaseModel<Object>> upHeadImg(@Part List<MultipartBody.Part> parts);
public interface UpLoadView extends BaseView {
    void onUpHeadImgSuccess(BaseModel<Object> o);
}

public class UpLoadPresenter extends BasePresenter<UpLoadView> {
    public UpLoadPresenter(UpLoadView baseView) {
        super(baseView);
    }

    public void upHeadImgApi(List<MultipartBody.Part> parts) {
        addDisposable(apiServer.upHeadImg(parts), new BaseObserver(baseView) {
            @Override
            public void onSuccess(Object o) {
                baseView.onUpHeadImgSuccess((BaseModel<Object>) o);
            }

            @Override
            public void onError(String msg) {
                if (baseView != null) {
                    baseView.showError(msg);
                }
            }
        });
    }
}
@Override
public void onClick(View v) {
    /**
     * 俩个参数  一个是图片集合路径   一个是和后台约定的Key,如果后台不需要,随便写都行
     */
  List<String> strings=new ArrayList<>();
    for (int i=0;i<100;i++){
        strings.add("tupian.lujing");
    }
    mPresenter.upHeadImgApi(RetrofitUtil.filesToMultipartBodyParts(RetrofitUtil.initImages(strings), "tupian.key"));
}
3、图片参数混合上传

首先创建接口,注意注解需要用@Multipart 参数形式
@PartMap Map<String, RequestBody> map,
@Part List<MultipartBody.Part> parts
注:Map中可以用String也可以用RequestBody

@Multipart
@POST("api/Express/add")
Observable<BaseModel<Object>> expressAdd(@PartMap Map<String, RequestBody> map,
                                             @Part List<MultipartBody.Part> parts);
public interface UpLoadView extends BaseView {
    void onExpressAddSuccess(BaseModel<Object> o);
}
public class UpLoadPresenter extends BasePresenter<UpLoadView> {
    public UpLoadPresenter(UpLoadView baseView) {
        super(baseView);
    }

    public void expressAdd(String title, String content, List<MultipartBody.Part> parts) {
        HashMap<String, RequestBody> params = new HashMap<>();
        params.put("title", RetrofitUtil.convertToRequestBody(title));
        params.put("content", RetrofitUtil.convertToRequestBody(content));
        addDisposable(apiServer.expressAdd(params, parts), new BaseObserver(baseView) {
            @Override
            public void onSuccess(Object o) {
                baseView.onExpressAddSuccess((BaseModel<Object>) o);
            }

            @Override
            public void onError(String msg) {
                if (baseView != null) {
                    baseView.showError(msg);
                }
            }
        });
    }
}
@Override
    public void onClick(View v) {
        /**
         * 俩个参数  一个是图片集合路径   一个是和后台约定的Key,如果后台不需要,随便写都行
         */
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            strings.add("tupian.lujing");
        }
        mPresenter.expressAdd(
                "title",
                "content",
                RetrofitUtil.filesToMultipartBodyParts(RetrofitUtil.initImages(strings), "tupian.key"));
    }

这样看起来会简洁明了,MVP框架连接 传送
能帮助到大家的点个赞支持一下,谢谢

上一篇下一篇

猜你喜欢

热点阅读