今天利用AsyncHttpClient架構實作将圖檔上傳到伺服器。
步驟和思路很簡單主要分為三步:
将圖檔bitmap進行base64編碼;
将編碼後的String通過AsyncHttpClient上傳給伺服器的php;
php中将擷取的String利用base64解碼儲存到伺服器;
其中android端Java代碼如下:
private void sendImage(Bitmap bt)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bt.compress(Bitmap.CompressFormat.JPEG, 60, stream);
byte[] bytes = stream.toByteArray();
//将bitmap進行Base64編碼
String img = new String(Base64.encode(bytes, Base64.DEFAULT));
AsyncHttpClient cilent = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.add("img", img);
params.add("userName", userName);//這裡由于需要,多傳入了一個參數,讀者可以忽略
System.out.println("params"+params.toString());
cilent.post(sendImageUrl, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// TODO Auto-generated method stub
Toast.makeText(PersonalMessage.this, "上傳成功", 1).show();
}
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
// TODO Auto-generated method stub
Toast.makeText(PersonalMessage.this, "上傳失敗", 1).show();
}
});
}
伺服器端php代碼:
$filename = "images/".$_POST['userName'];
$file = fopen($filename.".jpg","w");
$date = base64_decode($_POST['img']);
fwrite($file,$date);
fclose($file);
?>
這樣就OK了!