1. 程式人生 > >Android 測試上傳頭像到伺服器

Android 測試上傳頭像到伺服器

現在很多的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);
			}
		}
	}
對選擇的圖片進行處理後再上傳
/**上傳圖片到伺服器*/
	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);
	}
最後注意要在AndroidManifest.xml中加入相應的許可權
     <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;