[android/php] 안드로이드에서 서버에 사진 이미지 전송하기
안드로이드 코드
private void uploadPhoto(final Bitmap bitmap){ Thread thread = new Thread(new Runnable() { public void run() { ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte [] ba = bao.toByteArray(); String ba1 = Base64.encodeToString(ba, Base64.DEFAULT); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("image", ba1)); try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://10.0.2.2:80/android/base.php");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post); //HttpEntity entity = response.getEntity(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); thread.start(); }
위처럼 쓰레드로 감싸는 이유는, 허니콤 부터 Network 관련 부분을 쓰레드로 감싸지 않으면 Exception을 띄우게 해놨기 때문이다. 무슨 익셉션인지는 까먹었다.. 여튼 저렇게 쓰레드로 감싸야 한다!
서버 코드
<?php
$base=$_REQUEST['image']; echo $base; // base64 encoded utf-8 string $binary=base64_decode($base); // binary, utf-8 bytes header('Content-Type: bitmap; charset=utf-8'); // print($binary); //$theFile = base64_decode($image_data); $file = fopen('test.jpg', 'wb'); fwrite($file, $binary); fclose($file); echo '<img src=test.jpg>'; ?>
정말 간단하다! 아 그리고 안드로이드에 Internet permission 추가하는거 잊지 말 것.
* http://javaexpert.tistory.com/368에 있는 내용을 일부 수정 하여 게시함.