【发布时间】:2012-03-07 12:14:13
【问题描述】:
我目前正在尝试通过 Android 将图像上传到 PHP 服务器。以下是代码:
//Android上的代码段
bm = BitmapFactory.decodeFile(imagePath); //imagePath is the path of the image in my SD card
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);//compressing image
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://domain.com/upload_image.php");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse res = client.execute(post);
HttpEntity entity = res.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag","Error in http connection "+e.toString());
}
//PHP服务器上的代码段(upload_image.php)
<?php
$base=$_REQUEST['image'];
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('test.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
?>
我未能将图像上传到服务器,其中 test.jpg 从未出现在服务器上。我从我的智能手机运行程序,而不是模拟器。
【问题讨论】: