activity_main
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/main"
tools:context="com.example.m.uploadimage.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/ic_back"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:paddingRight="30dp"
android:text="个人信息"
android:textSize="25sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:gravity="center_vertical"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="头像"
android:textSize="20sp"/>
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/myHead"
android:src="@mipmap/ic_launcher"/>
</LinearLayout>
</LinearLayout>
pop_layout
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/pai"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="拍照"
android:textSize="30sp"/>
<TextView
android:id="@+id/xiangce"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="相册"
android:textSize="30sp"/>
<TextView
android:id="@+id/quxiao"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="取消"
android:textSize="30sp"/>
</LinearLayout>
MainActivity
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private CircleImageView circleImageView;
private PopupWindow popupWindow;
private String imagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化界面
initViews();
}
private void initViews() {
circleImageView = findViewById(R.id.myHead);
circleImageView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.myHead:
//弹出pop
View view = LayoutInflater.from(this).inflate(R.layout.pop_layout, null);
//找到pop里面的选项
TextView pai = view.findViewById(R.id.pai);
pai.setOnClickListener(this);
TextView xiangce = view.findViewById(R.id.xiangce);
xiangce.setOnClickListener(this);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
popupWindow.setOutsideTouchable(true);
//显示
popupWindow.showAtLocation(MainActivity.this.findViewById(R.id.main),
Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
break;
case R.id.pai:
//启动系统相机
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//开启相机之前,设置图片保存的路径
imagePath = Environment.getExternalStorageDirectory().getPath() + "myIcon.png";
File file = new File(imagePath);
//创建Uri
Uri imageUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//设置完毕开启Activity
startActivityForResult(intent, 0);
//pop消失
popupWindow.dismiss();
break;
case R.id.xiangce:
Intent intent1 = new Intent();
intent1.addCategory(Intent.CATEGORY_OPENABLE);
intent1.setType("image/*");
if (Build.VERSION.SDK_INT < 19) {
intent1.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent1.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
startActivityForResult(intent1, 1);
break;
}
}
private static final String TAG = "MainActivity---";
//重写
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//判断
switch (requestCode) {
case 0:
//获取图片的uri
if (data != null) {
Bitmap bitmap = data.getParcelableExtra("data");
//放入图片
circleImageView.setImageBitmap(bitmap);
//上传头像
//得到图片路径
File imageFile = new File(imagePath);
OKHttpUtils okHttpUtils = OKHttpUtils.getInstance();
HashMap<String, String> map = new HashMap<>();
map.put("uid", "71");
map.put("source", "android");
okHttpUtils.upLoadFile("https://www.zhaoapi.cn/file/upload", imageFile, map);
okHttpUtils.setUpListene(new UpListener() {
@Override
public void upSuccess(String json) {
Log.d(TAG, "upSuccess() returned: " + json);
Toast.makeText(MainActivity.this, "chengg000", Toast.LENGTH_SHORT).show();
}
@Override
public void upError(String e) {
Log.d(TAG, "upError() returned: " + e);
Toast.makeText(MainActivity.this, "shibai----", Toast.LENGTH_SHORT).show();
}
});
}
break;
case 1:
Uri uri = data.getData();
//相册返回的是uri,这里需要将uri转成path路径
String path = getImageAbsolutePath(this, uri);
Log.d(TAG, "路径---- " + uri + "--" + path);
File imageFile = new File(path);//创建文件
//开始调用okhttputils进行网络上传
OKHttpUtils okHttpUtils = OKHttpUtils.getInstance();
HashMap<String, String> map = new HashMap<>();
map.put("uid", "71");
map.put("source", "android");
okHttpUtils.upLoadFile("https://www.zhaoapi.cn/file/upload", imageFile, map);
//回调
okHttpUtils.setUpListene(new UpListener() {
@Override
public void upSuccess(String json) {
Log.d(TAG, "upSuccess() returned: " + json);
Toast.makeText(MainActivity.this, "chengg000", Toast.LENGTH_SHORT).show();
}
@Override
public void upError(String e) {
Log.d(TAG, "upError() returned: " + e);
Toast.makeText(MainActivity.this, "shibai----", Toast.LENGTH_SHORT).show();
}
});
break;
}
}
//以下都是将Uri---》path路径的代码
public static String getImageAbsolutePath(Context context, Uri imageUri) {
if (context == null || imageUri == null)
return null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
if (isExternalStorageDocument(imageUri)) {
String docId = DocumentsContract.getDocumentId(imageUri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(imageUri)) {
String id = DocumentsContract.getDocumentId(imageUri);
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(imageUri)) {
String docId = DocumentsContract.getDocumentId(imageUri);
String[] split = docId.split(":");
String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} // MediaStore (and general)
else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(imageUri))
return imageUri.getLastPathSegment();
return getDataColumn(context, imageUri, null, null);
}
// File
else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
return imageUri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
String column = MediaStore.Images.Media.DATA;
String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
OKHttpUtils
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by M on 2018/1/16.
*/
public class OKHttpUtils {
private UpListener upListener;
private MyHandler myHandler = new MyHandler();
//单利
private static OKHttpUtils okHttpUtils = null;
public static OKHttpUtils getInstance() {
if (okHttpUtils == null) {
okHttpUtils = new OKHttpUtils();
}
return okHttpUtils;
}
//上传头像
public void upLoadFile(String url, File file, final Map<String, String> map) {
//设置超时时间及缓存
OkHttpClient mOkHttpClient = new OkHttpClient();
MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);
//媒体类型
final MediaType mediaType = MediaType.parse("image/png");
//向mBody中添加文件,也就是我们的图片
mbody.addFormDataPart("file", file.getName(), RequestBody.create(mediaType, file));
//添加其他参数
Set<String> keys = map.keySet();
for (String key : keys) {
String value = map.get(key);
mbody.addFormDataPart(key,value);
}
//闭环
RequestBody requestBody = mbody.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = myHandler.obtainMessage();
message.what = 0;
message.obj = e.getMessage();
myHandler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message = myHandler.obtainMessage();
message.what = 1;
message.obj = response.body().string();
myHandler.sendMessage(message);
}
});
}
//外部访问的方法
public void setUpListene(UpListener upListener) {
this.upListener = upListener;
}
//handler
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
String e = (String) msg.obj;
upListener.upError(e);
break;
case 1:
String json = (String) msg.obj;
upListener.upSuccess(json);
break;
}
}
}
}
UpListener
public interface UpListener {
void upSuccess(String json);
void upError(String e);
}
依赖
compile 'de.hdodenhof:circleimageview:2.2.0'
compile 'com.squareup.okhttp3:okhttp:3.3.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"/>