无法获取位图上传到PHP服务器?
问题描述:
我试图让我的应用程序将使用相机拍摄的图像上传到服务器。我知道这不是服务器,因为我可以毫无问题地访问网址。我得到Error in http connection android.os.NetworkOnMainThreadException
作为错误。这是我正在尝试使用的代码。无法获取位图上传到PHP服务器?
public void uploadFile(Bitmap file) {
Bitmap bitmapOrg = file;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.info/appserver/upload.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
答
网络活动无法在主线程(UI线程)上完成,因为它会严重影响您的应用程序对用户的感受。查看training doc on doing network access using AsyncTasks获取解决方案。
谢谢,我得到它的工作! – 2013-03-10 22:59:07