现在很多的app中都有用户注册登录以及头像修改的功能, 下面就我碰到的上传头像到服务器中做个简单的介绍。
既然要上传头像, 那么Android中图片的来源有两种方式 :通过文件管理器、通过拍照
1:文件管理器(图库)
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");// 选择图片类型
// 在onActivityResult中处理选择结果
startActivityForResult(intent, PICTURE_REQUEST_CODE);
2:拍照
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 请求拍照的Action
// 在onActivityResult中处理拍照结果
startActivityForResult(intent, CAMERA_REQUEST_CODE);
通过Intent来请求图片资源, 那么请求到的图片资源怎么去获取呢?此时就可以通过Activity中的 onActivityResult方法来对图片进行处理
protected void onActivityResult(int requestCode, int resultCode, Intent data)对选择的图片进行处理后再上传
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null)
{
Uri uri = data.getData();
Bitmap bitmap = null;
if (null != uri)
{
String imgPath = null;
ContentResolver resolver = this.getContentResolver();
String[] columns = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
cursor = resolver.query(uri, columns, null, null, null);
if (Build.VERSION.SDK_INT > 18)// 4.4以后文件选择发生变化,判断处理
{
// http://blog.csdn.net/tempersitu/article/details/20557383
if (requestCode == PICTURE_REQUEST_CODE)// 选择图片
{
imgPath = uri.getPath();
if (!TextUtils.isEmpty(imgPath)
&& imgPath.contains(":"))
{
String imgIndex = imgPath.split(":")[1];
cursor = resolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
columns, "_id=?", new String[] { imgIndex },
null);
}
}
}
if (null != cursor && cursor.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(columns[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
}
if (!TextUtils.isEmpty(imgPath))
{
bitmap = genBitmap(imgPath);
}
}
else if (requestCode == CAMERA_REQUEST_CODE)// 拍照
{
// 拍照时,注意小米手机不会保存图片到本地,只可以从intent中取出bitmap, 要特殊处理
Object object = data.getExtras().get("data");
if (null != object && object instanceof Bitmap)
{
bitmap = (Bitmap) object;
}
}
if (null != bitmap)
{
upload(bitmap);
}
}
}
/**上传图片到服务器*/最后注意要在AndroidManifest.xml中加入相应的权限
private void upload(final Bitmap bitmap)
{
new AsyncTask<Bitmap, Void, String>()
{
ProgressDialog progressDialog;
protected void onPreExecute()
{
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setMessage("正在和服务器通信中……");
progressDialog.show();
};
@Override
protected String doInBackground(Bitmap... params)
{
try
{
//此处没有判断是否有sd卡
File dirFile = new File("/mnt/sdcard/android/cache");
if(!dirFile.exists())
{
dirFile.mkdirs();
}
File file = new File(dirFile, "photo.png");
if (params[0].compress(CompressFormat.PNG, 50,
new FileOutputStream(file)))
{
System.out.println("保存图片成功");
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(UPLOAD_URL);
MultipartEntity entity = new MultipartEntity();
// 通过RSA加密后的用户名
String miUserName = "GuKDdJVZXBpjrX3JmumCDkgIzjlGcEfpy9ty+Gpwt5fNDopuM1KqNMTmMy0eflplRoJFj8A0tw4e66ib+wfPB7YXxSk836s+yk7MvrmF289u5o2nBzb+roEGZhEjlmCGheXgC4EBWcHqR2Sp+lVzQLE/yELJE9uXG1YKQuYqvpY=";
entity.addPart("acc", new StringBody(miUserName));
entity.addPart("ext", new StringBody("png"));
entity.addPart("img", new FileBody(file));
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
InputStream in = response.getEntity().getContent();
byte[] buffer = new byte[1024];
int len = 0;
StringBuffer stringBuffer = new StringBuffer();
while ((len = in.read(buffer)) != -1)
{
stringBuffer.append(new String(buffer, 0, len,
"utf-8"));
}
System.out.println("stringBuffer = "
+ stringBuffer.toString().trim());
file.delete();//删除文件
return stringBuffer.toString().trim();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
if (!TextUtils.isEmpty(result))
{
try
{
JSONObject jsonObject = new JSONObject(result);
if (null != jsonObject
&& "1".equals(jsonObject.opt("result")))
{// 上传成功
mIvImageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, "上传成功",
Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(MainActivity.this, "上传失败",
Toast.LENGTH_SHORT).show();
}
};
}.execute(bitmap);
}
/**通过给定的图片路径生成对应的bitmap*/
private Bitmap genBitmap(String imgPath)
{
BitmapFactory.Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgPath, options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
int widthSample = (int) (imageWidth / mWH);
int heightSample = (int) (imageHeight / mWH);
// 计算缩放比例
options.inSampleSize = widthSample < heightSample ? heightSample
: widthSample;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imgPath, options);
}
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
上面代码中用的一些变量
private static final String UPLOAD_URL = "http://comments.roboo.com/photoUpload";
private static final int CAMERA_REQUEST_CODE = 222;
private static final int PICTURE_REQUEST_CODE = 444;
/**上传图片的宽度和高度*/
private int mWH = 90;// 单位dp
private ImageView mIvImageView;
private Button mBtnCamera;
private Button mBtnPicture;
下载地址:http://download.csdn.net/detail/u012612952/8298037