导入依赖:
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
创建一个HttpService接口类:
public interface HttpService {
@Multipart
@POST
Observable<ResponseBody> upLoad(@Url String url,
@HeaderMap Map<String, String> map,
@Part MultipartBody.Part part);
}
创建一个HttpUtils类:
public class HttpUtils {
private Map<String, String> headMap = new HashMap<>();
public HttpUtils setHead(Map<String, String> headMap) {
this.headMap = headMap;
return this;
}
public HttpUtils upload(String url, File file) {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://172.17.8.100")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
HttpService service = retrofit.create(HttpService.class);
MediaType mediaType = MediaType.parse("multipart/form-data;charset=UTF-8");
RequestBody body = RequestBody.create(mediaType, file);
MultipartBody.Part part = MultipartBody.Part.createFormData("image", file.getName(), body);
Observable<ResponseBody> ob = service.upLoad(url, headMap, part);
ob.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
mHttpListener.success(responseBody.string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
mHttpListener.fail(e.getMessage());
}
@Override
public void onComplete() {
}
});
return this;
}
private HttpListener mHttpListener;
public void result(HttpListener mHttpListener) {
this.mHttpListener = mHttpListener;
}
public interface HttpListener {
void success(String data);
void fail(String error);
}
}
MainActivity类:
public class MainActivity extends AppCompatActivity { private String pathPic = Environment.getExternalStorageDirectory().getAbsolutePath() + "/1610b.jpg";//图片路径 private ImageView mPic; @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) {//相册 Uri uri = data.getData(); cropPhoto(uri);//执行裁剪 } else if (requestCode == 2) {//相机 Bitmap bitmap = BitmapFactory.decodeFile(pathPic); mPic.setImageBitmap(bitmap); upLoad(new File(pathPic)); } else if (requestCode == 3) {//裁剪过后 if (data != null) { Bundle es = data.getExtras(); if (es == null) { return; } Bitmap bitmap = es.getParcelable("data"); mPic.setImageBitmap(bitmap);//设置给imageView saveBitmapFile(bitmap); upLoad(new File(pathPic)); } } } //执行裁剪 private void cropPhoto(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); // // aspectX aspectY 是宽高的比例 // intent.putExtra("aspectX", 1); // intent.putExtra("aspectY", 1); // // outputX outputY 是裁剪图片宽高 // intent.putExtra("outputX", 127); // intent.putExtra("outputY", 127); // intent.putExtra("scale", true); // intent.putExtra("noFaceDetection", false);//不启用人脸识别 intent.putExtra("return-data", true); startActivityForResult(intent, 3); } //上传头像 private void upLoad(File file) { Map<String, String> headMap = new HashMap<>(); headMap.put("userId", "2325"); headMap.put("sessionId", "15565946273102325"); new HttpUtils().setHead(headMap).upload("small/user/verify/v1/modifyHeadPic", file) .result(new HttpUtils.HttpListener() { @Override public void success(String data) { Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG).show(); } @Override public void fail(String error) { Toast.makeText(MainActivity.this, error, Toast.LENGTH_LONG).show(); } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPic = (ImageView) findViewById(R.id.iv_pic); findViewById(R.id.btn_photo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //打开相机 Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(pathPic))); startActivityForResult(intent2, 2);//采用ForResult打开 } }); findViewById(R.id.btn_photo_2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //打开相册 Intent intent1 = new Intent(Intent.ACTION_PICK, null); intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent1, 1); } }); } //Bitmap对象保存图片文件 public void saveBitmapFile(Bitmap bitmap) { File file = new File(pathPic);//将要保存图片的路径 try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } }