本文章使用的是Retrofit rxjava网络工具类 是世面上使用的网络工具类
不多说直接上代码
1.导入依赖 implementation ‘com.github.wildma:PictureSelector:1.1.1’
implementation 'com.github.wildma:PictureSelector:1.1.1'
2.在项目的build.gradle中 找到一下两个地方
repositories {
google()
jcenter()
maven { url "https://jitpack.io" }//所添加的
}
//还有这个
allprojects {
repositories {
google()
jcenter()
maven { url "https://jitpack.io" }//所需添加的
}
}
3.在网络工具类当中
//xiangji
public RequestBody getRequsetBody(List<File> files, HashMap<String,String> map){
// if (map.size() < 1){
// return null;
// }
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (Map.Entry<String,String> entry:map.entrySet()){
Log.i("xxx","key = "+entry.getKey()+"value = "+entry.getValue());
builder.addFormDataPart(entry.getKey(),entry.getValue()+"");
}
for (int i = 0; i <files.size(); i++){
builder.addFormDataPart("image",files.get(i).getName(),RequestBody.create(MediaType.parse("image/jepg"),files.get(i)));
}
return builder.build();
}
4.bean类
public class UpLoadHeadPicBean {
private String headPath;
private String message;
private String status;
public String getHeadPath() {
return headPath;
}
public void setHeadPath(String headPath) {
this.headPath = headPath;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
5.在这个接口中
public interface Apis {
//这里是你自己要换的地址
@POST("user/v1/verify/uploadHeadPic")
Observable<UpLoadHeadPicBean> getUpLoadHeadPicBean(@Body RequestBody body);
}
6.在activity中设置头像点击事件
PictureSelector.create(MyXiangActivity.this, PictureSelector.SELECT_REQUEST_CODE).selectPicture(true, 200, 200, 1, 1);
7.在onActivityResult中回调
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK&&requestCode==PictureSelector.SELECT_REQUEST_CODE){
if (data != null) {
String stringExtra = data.getStringExtra(PictureSelector.PICTURE_PATH);
File file = new File(stringExtra);
ArrayList<File> files = new ArrayList<>();
files.add(file);
HashMap<String, String> map = new HashMap<>();
RequestBody requsetBody = RetrofitManager.getInstance().getRequsetBody(files, map);
RetrofitManager.getInstance().getApis().getUpLoadHeadPicBean(requsetBody)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<UpLoadHeadPicBean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(UpLoadHeadPicBean upLoadHeadPicBean) {
Toast.makeText(MyXiangActivity.this, ""+upLoadHeadPicBean.getMessage(), Toast.LENGTH_SHORT).show();
//如果土司上传成功 你还得在这里面做一个ui更新
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
}