//添加清單文件依賴
? <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() {
//創(chuàng)建文件用于保存圖片getExternalCacheDir
? ? mFile =new File(getExternalCacheDir(), System.currentTimeMillis() +".jpg");
if (!mFile.exists()) {
try {
mFile.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
}
//適配7.0,? 等到對應(yīng)的mImageUri路徑地址
? ? if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mImageUri = Uri.fromFile(mFile);
}else {
//第二個參數(shù)要和清單文件中的配置保持一致
? ? ? ? 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) {//判斷回調(diào)成功
? ? ? ? if (requestCode ==CAMERA_CODE) {//拍照
//拍照后的圖片上傳
? ? ? ? ? ? uploadFile(mFile);
}else if (requestCode ==ALBUM_CODE) {//相冊
//獲取到相冊選中后的圖片URI路徑
? ? ? ? ? ? Uri imageUri = data.getData();
//文件上傳温眉,將Uri路徑轉(zhuǎn)換為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);
// 創(chuàng)建多媒體 請求對象
? ? 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();
}
}
}
});
}
});
}