首先我们先要写一个接口,上传头像必须要写@Multipart注解
@Multipart
@POST("small/user/verify/v1/modifyHeadPic")
Observable<ResponseBody> uploadPic(@Part MultipartBody.Part part);
紧接着就需要写一下我门的工具类了
public class RetrofitUtils {
public static RetrofitUtils mInstance;
private final Retrofit retrofit;
private final UserService userService;
public static RetrofitUtils getmInstance(){
if(mInstance==null){
synchronized (RetrofitUtils.class){
if(mInstance==null){
mInstance = new RetrofitUtils();
}
}
}
return mInstance;
}
private RetrofitUtils(){
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("userId", "159")
.addHeader("sessionId", "1562331135438159")
.build();
return chain.proceed(request);
}
})
.writeTimeout(5,TimeUnit.SECONDS)
.connectTimeout(5,TimeUnit.SECONDS)
.readTimeout(5,TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("http://172.17.8.100/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
userService = retrofit.create(UserService.class);
}
public void uploadPic(File file, final HttpListener httpListener){
MediaType type = MediaType.parse("multi/form_data;charset=utf-8");
RequestBody body = RequestBody.create(type, file);
MultipartBody.Part part = MultipartBody.Part.createFormData("image",file.getName(),body);
userService.uploadPic(part)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
httpListener.Success(responseBody.string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
httpListener.Failure(e.getMessage());
}
@Override
public void onComplete() {
}
});
}
public interface HttpListener{
void Success(String data);
void Failure(String error);
}
}
接下来就需要写我们的mvp了,首先我们需要写的是契约类
public interface LoadContract {
public abstract class lLoadPresenter{
public abstract void getCart(File file);
}
interface lLoadModel{
void getCart(File file,CallBack callBack);
}
interface lLoadView{
void Success(String result);
void Failure(String msg);
}
interface CallBack{
void Success(String result);
void Failure(String msg);
}
}
然后就是我们的model层
public class LoadModel implements LoadContract.lLoadModel {
@Override
public void getCart(File file, final LoadContract.CallBack callBack) {
RetrofitUtils.getmInstance().uploadPic(file, new RetrofitUtils.HttpListener() {
@Override
public void Success(String data) {
callBack.Success(data);
}
@Override
public void Failure(String error) {
callBack.Failure(error);
}
});
}
}
写完model紧接着就是我们的presenter层
public class LoadPresenter extends LoadContract.lLoadPresenter implements LoadContract.CallBack{
private LoadContract.lLoadView lLoadView;
private LoadModel loadModel;
public LoadPresenter(LoadContract.lLoadView lLoadView) {
this.lLoadView = lLoadView;
loadModel = new LoadModel();
}
@Override
public void getCart(File file) {
loadModel.getCart(file,this);
}
@Override
public void Success(String result) {
lLoadView.Success(result);
}
@Override
public void Failure(String msg) {
lLoadView.Failure(msg);
}
}
接下来也就是最后一步操作了,在我们的展示页面完善操作
public class MainActivity extends AppCompatActivity implements LoadContract.lLoadView {
@BindView(R.id.lv)
ImageView mLv;
@BindView(R.id.title)
TextView mTitle;
//上传路径
private LoadPresenter loadPresenter;
private PopupWindow popupWindow;
private SharedPreferences.Editor edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
SharedPreferences sp = getSharedPreferences("sp", Context.MODE_PRIVATE);
edit = sp.edit();
String headPath = sp.getString("headPath", "");
Uri uri = Uri.parse(sp.getString("ss",""));
Glide.with(getApplicationContext()).load(uri).into(mLv);
mTitle.setText(headPath);
//引用presenter
loadPresenter = new LoadPresenter(this);
mLv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//引用popwindow布局
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop,null);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
popupWindow.setContentView(view);
popupWindow.setOutsideTouchable(true);
//获取popwindow的控件
TextView xj = view.findViewById(R.id.xj);
TextView xc = view.findViewById(R.id.xc);
TextView qx = view.findViewById(R.id.qx);
xj.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"head.jpg")));
startActivityForResult(intent,2);
popupWindow.dismiss();
}
});
xc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent,1);
popupWindow.dismiss();
}
});
qx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
//隐藏主页面
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main,null);
popupWindow.showAtLocation(view1,Gravity.BOTTOM,0,0);
}
});
}
//系统裁剪
public void corpPhone(Uri uri){
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri,"image/*");
intent.putExtra("return-data",true);
startActivityForResult(intent,3);
}
//保存到sd卡
private void setPicToView(Bitmap bitmap){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/head.jpg");
try {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 1:
if(resultCode==RESULT_OK){
corpPhone(data.getData());
}
break;
case 2:
if(resultCode==RESULT_OK){
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/head.jpg";
File temp = new File(Environment.getExternalStorageDirectory()+"/head.jpg");
Bitmap bitmap = BitmapFactory.decodeFile(path);
mLv.setImageBitmap(bitmap);
corpPhone(Uri.fromFile(temp));
loadPresenter.getCart(new File(path));
}
break;
case 3:
if(data!=null){
Bundle extras = data.getExtras();
if(extras==null){
return;
}
Bitmap head = extras.getParcelable("data");
mLv.setImageBitmap(head);
setPicToView(head);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/head.jpg";
loadPresenter.getCart(new File(path));
}
break;
}
}
@Override
public void Success(String result) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
//解析Bean
UserBean userBean = new Gson().fromJson(result,UserBean.class);
//存值
edit.putString("ss",userBean.getHeadPath());
edit.putString("headPath",result);
//提交
edit.commit();
}
@Override
public void Failure(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}