okhttpUtils是okhttp的一个工具类,并且安卓7以上uri获取需要配置共享目录,可以参考我的另一篇博文,这里不再赘述。
点我跳转到另一篇博文
首先我的示例中这个需求的应用场景是更换头像,先简单看一下页面:
流程是先选择图片,引导用户进入相册或文件管理器选择图片后直接跳转到裁剪页面裁剪,并将裁剪后的图片显示到上方控件中并通过okhttpUtils上传至服务器,代码如下:
uploadImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent selectImg = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
selectImg.setType("image/*");
startActivityForResult(selectImg, 666);
}
});
changeUserIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(imgUrlBefore.equals(imgUrlAfter))
{
Toasty.info(ChangeUserImg.this,"请先上传一张新图片",Toast.LENGTH_SHORT).show();
}else{
final MaterialDialog waitForDialog = new MaterialDialog.Builder(ChangeUserImg.this)
.content("正在修改...")
.progress(true,-1)
.cancelable(false)
.build();
waitForDialog.show();
Log.w(TAG,imgUrlAfter);
String host = new Defines().SERVER_HOST+"/user/changeUserImg";
OkHttpUtils
.post()
.url(host)
.addParams("token",token)
.addParams("img_url",imgUrlAfter)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
waitForDialog.hide();
Toasty.error(ChangeUserImg.this, "服务器请求失败", Toast.LENGTH_SHORT, true).show();
}
@Override
public void onResponse(String response, int id) {
waitForDialog.hide();
try {
JSONObject jsonObject = new JSONObject(response);
int code = jsonObject.getInt("code");
if (code==200) {
Toasty.success(ChangeUserImg.this,jsonObject.getString("msg"),Toast.LENGTH_SHORT, true).show();
finish();
} else {
Toasty.error(ChangeUserImg.this,jsonObject.getString("msg"), Toast.LENGTH_SHORT, true).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(ChangeUserImg.this,"修改失败",Toast.LENGTH_LONG).show();
}
}
});
}
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case 666:
{
Uri uri = data.getData();
cutImg(uri); //选取图片成功后进行裁剪
break;
}
case 888:
{
final MaterialDialog waitForDialog = new MaterialDialog.Builder(ChangeUserImg.this)
.content("正在上传...")
.progress(true,-1)
.cancelable(false)
.build();
waitForDialog.show();
String cachePath;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
cachePath = ChangeUserImg.this.getExternalCacheDir().getPath();
} else {
cachePath = ChangeUserImg.this.getFilesDir().getAbsolutePath();
}
final File userImgFile = new File(cachePath+"/userImg.jpg");
ChangeUserImg.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(userImgFile)));
String host = new Defines().SERVER_HOST+"uploadUserImage";
OkHttpUtils
.post()
.url(host)
.addFile("img","userImg.jpg",userImgFile) //请求中添加文件
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
waitForDialog.hide();
Toasty.error(ChangeUserImg.this, "服务器请求失败", Toast.LENGTH_SHORT, true).show();
}
@Override
public void onResponse(String response, int id) {
waitForDialog.hide();
try {
JSONObject jsonObject = new JSONObject(response);
int code = jsonObject.getInt("code");
if (code==200) {
Toasty.success(ChangeUserImg.this,jsonObject.getString("msg"),Toast.LENGTH_SHORT, true).show();
ImageView userImg = findViewById(R.id.icon);
RequestOptions options = RequestOptions.circleCropTransform().placeholder(R.drawable.loading).error(R.drawable.error_img);
Glide.with(ChangeUserImg.this).load(jsonObject.getString("data")).apply(options).into(userImg);
imgUrlAfter = jsonObject.getString("data");
} else {
Toasty.error(ChangeUserImg.this,jsonObject.getString("msg"), Toast.LENGTH_SHORT, true).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(ChangeUserImg.this,"上传失败",Toast.LENGTH_LONG).show();
}
}
});
break;
}
}
}
}
public void cutImg(Uri inputUri)
{
Intent intent = new Intent("com.android.camera.action.CROP"); //使用系统的裁剪功能
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(inputUri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1); //裁剪比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 256); //输出尺寸
intent.putExtra("outputY", 256);
intent.putExtra("scale", true);
intent.putExtra("return-data",true);
String cachePath;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
cachePath = ChangeUserImg.this.getExternalCacheDir().getPath();
} else {
cachePath = ChangeUserImg.this.getFilesDir().getAbsolutePath();
}
File uriFile = new File(cachePath+"/userImg.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(uriFile));
startActivityForResult(intent, 888);
}