//添加清单文件依赖
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
/*打开相册*/
private void initData2() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//相册
openAlbum();
}else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},2000);
}
}
private void openAlbum() {
//启动相册
Intent intent =new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent,ALBUM_CODE);
}
/*打开相机*/
private void initData() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
//相机
openCamera();
}else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},1000);
}
}
@RequiresApi(api = Build.VERSION_CODES.FROYO)
private void openCamera() {
//创建文件用于保存图片getExternalCacheDir
mFile =new File(getExternalCacheDir(), System.currentTimeMillis() +".jpg");
if (!mFile.exists()) {
try {
mFile.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
}
//适配7.0, 等到对应的mImageUri路径地址
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mImageUri = Uri.fromFile(mFile);
}else {
//第二个参数要和清单文件中的配置保持一致
mImageUri = FileProvider.getUriForFile(this,"com.baidu.upload.provider",mFile);
}
//启动相机
Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,mImageUri);//将拍照图片存入mImageUri
startActivityForResult(intent,CAMERA_CODE);
}
//拍完照片后保存 上传头像
@Override
protected void onActivityResult(int requestCode,int resultCode,@Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode ==RESULT_OK) {//判断回调成功
if (requestCode ==CAMERA_CODE) {//拍照
//拍照后的图片上传
uploadFile(mFile);
}else if (requestCode ==ALBUM_CODE) {//相册
//获取到相册选中后的图片URI路径
Uri imageUri = data.getData();
//文件上传,将Uri路径转换为File对象
//处理uri,7.0以后的fileProvider 把URI 以content provider 方式 对外提供的解析方法
File file = getFileFromUri(imageUri,this);
if (file.exists()) {
uploadFile(file);
}
}
}
}
private File getFileFromUri(Uri imageUri, PersonalActivity personalActivity) {
if (imageUri ==null) {
return null;
}
switch (imageUri.getScheme()) {
case "content":
return getFileFromContentUri(imageUri, personalActivity);
case "file":
return new File(imageUri.getPath());
default:
return null;
}
}
private File getFileFromUri(Uri imageUri, PersonalActivity personalActivity) {
if (imageUri ==null) {
return null;
}
switch (imageUri.getScheme()) {
case "content":
return getFileFromContentUri(imageUri, personalActivity);
case "file":
return new File(imageUri.getPath());
default:
return null;
}
}
//OkHttp上传头像
private File getFileFromContentUri(Uri imageUri, PersonalActivity personalActivity) {
if (imageUri ==null) {
return null;
}
File file =null;
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
ContentResolver contentResolver = personalActivity.getContentResolver();
Cursor cursor = contentResolver.query(imageUri, filePathColumn,null,
null,null);
if (cursor !=null) {
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
cursor.close();
if (!TextUtils.isEmpty(filePath)) {
file =new File(filePath);
}
}
return file;
}
private void uploadFile(File mFile) {
String url ="http://yun918.cn/study/public/file_upload.php";
OkHttpClient client =new OkHttpClient.Builder()
.build();
// file-->RequestBody
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), mFile);
// 创建多媒体 请求对象
MultipartBody body =new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("key","H1808C")
.addFormDataPart("file", mFile.getName(), requestBody)
.build();
Request request =new Request.Builder()
.url(url)
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG,"onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response)throws IOException {
String string = response.body().string();
Gson gson =new Gson();
final UpLoadPictureBean upLoadBean = gson.fromJson(string, UpLoadPictureBean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (upLoadBean !=null) {
if (upLoadBean.getCode() ==200) {
Toast.makeText(PersonalActivity.this,upLoadBean.getRes(), Toast.LENGTH_SHORT).show();
SpUtil.setParam(Constants.HEADIMG,upLoadBean.getData().getUrl());
Glide.with(PersonalActivity.this).load(upLoadBean.getData().getUrl()).apply(requestOptions).into(mHeadPortrait);
Log.e(TAG,"run: " +upLoadBean.getData().getUrl());
}else {
Toast.makeText(PersonalActivity.this,upLoadBean.getRes(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
});
}