2012-03-05 6 views
5

나는 기본적으로 안드로이드에서 이미지를 업로드하고 PHP 서버에 업로드하려고하지만 여기는 내가이 코드 또는 이미지 업로드
와 어떤 연결도 안하고있어. 이 오류가 발생합니다.PHP 서버에 이미지를 업로드하고 phpmyadmin에 저장하는 방법

Error in http connection java.net.UnknownHostException: host name 

하지만 내 지식에 따라 올바른 연결과 php 파일을 올바른 도메인에 제공합니다. 내 코드에서 봐 : UploadImage.java

public class UploadImage extends Activity { 
InputStream inputStream; 
    @Override 
public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.main); 

     Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon); 
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want. 
     byte [] byte_arr = stream.toByteArray(); 
     String image_str = Base64.encodeBytes(byte_arr); 
     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

     nameValuePairs.add(new BasicNameValuePair("image",image_str)); 

     try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://server.com/uploadimage/uploadimage.php"); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      String the_string_response = convertResponseToString(response); 
      Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show(); 
     }catch(Exception e){ 
       Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show(); 
       System.out.println("Error in http connection "+e.toString()); 
     } 
    } 

    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{ 

     String res = ""; 
     StringBuffer buffer = new StringBuffer(); 
     inputStream = response.getEntity().getContent(); 
     int contentLength = (int) response.getEntity().getContentLength(); //getting content length….. 
     Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show(); 
     if (contentLength < 0){ 
     } 
     else{ 
       byte[] data = new byte[512]; 
       int len = 0; 
       try 
       { 
        while (-1 != (len = inputStream.read(data))) 
        { 
         buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer….. 
        } 
       } 
       catch (IOException e) 
       { 
        e.printStackTrace(); 
       } 
       try 
       { 
        inputStream.close(); // closing the stream….. 
       } 
       catch (IOException e) 
       { 
        e.printStackTrace(); 
       } 
       res = buffer.toString();  // converting stringbuffer to string….. 

       Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show(); 
       //System.out.println("Response => " + EntityUtils.toString(response.getEntity())); 
     } 
     return res; 
    } 

}

의 PHP 코드 :이 문제를 알고

<?php 
$base=$_REQUEST['image']; 
$binary=base64_decode($base); 
header('Content-Type: bitmap; charset=utf-8'); 
$file = fopen('uploaded_image.jpg', 'wb'); 
fwrite($file, $binary); 
fclose($file); 
echo 'Image upload complete!!, Please check your php file directory……';?> 

어느 하나? 하나는 PHP 파일에서 MySQL의 데이터베이스에 저장하고 viceversa에 가져 오는 방법을 알고있는 경우

Error in http connection java.net.UnknownHostException: host name 

HttpPost 연결을 할 수 없다는 것을 의미합니다 ... 문제는 매우 분명하다 ... 여기

+1

imagecreatefromstring() 함수를 참고 uploadimage.php 잘 작동합니다. 에뮬레이터의 inbuilt 브라우저를 열어 인터넷 연결을 확인할 수도 있습니다. – Dharmendra

답변

8

날을 제안 해주십시오 제공 한 호스트 이름을 사용합니다. 제공된 호스트 이름을 알 수 없기 때문에. 당신이이 줄에서 호스트 이름이 걸릴 경우

는 :

HttpPost httppost = new HttpPost("http://server.com/uploadimage/uploadimage.php"); 

을 무슨 일이 일어 동일한 장치의 브라우저에 넣어 ... 난 당신이 호스트에 연결할 수 없습니다라고 오류가 발생합니다 제안합니다.

<uses-permission android:name="android.permission.INTERNET" /> 

은 또한 당신이 JPEG 사용하는 경우 PHP 파일은 다음 헤더가 포함되어 있는지 확인하십시오 :

header('Content-Type: image/jpg'); 
+0

브라우저에서이 줄을 사용하면 현재 길이가 -1로 줄어 듭니다. 다음에 할 일을 볼 수 있습니다. – Rizvan

1

확인 호스트 구성이 다음 작동하면 난 당신이 다음 줄이 매니페스트에 확인하시기 파일 업로드에 적합한 헤더를 선택하십시오. 귀하의 PHP 코드에서 잘못된 헤더 유형을 부여했습니다.

1

ManseUK이 매니페스트에 권한을 추가한다고 말한대로 추천합니다. 이 오류는 매우 불분명하지만 종종 이것은 나를 위해 작동 <uses-permission android:name="android.permission.INTERNET" />

3
1. Need to add Internet permission in android manifest file . 
<uses-permission android:name="android.permission.INTERNET" /> 

2. Every Time i used to see image using url but unable to see because i didnt added 
     echo "<img src=test.jpg>"; 
3.$file = fopen('test.jpg', 'wb'); 

4. final thing is i have to change header file as : 

header('Content-Type: image/jpg; charset=utf-8'); 
0

을 추가하여 해결 :

//이
bitmap.compress을 JPEG로 비트 맵 압축 형식을 변경 (Bitmap.CompressFormat.JPEG를, 100, baos);

// 다음

// 당신이 에뮬레이터에서 테스트하는 경우, 일단은이 예외를주고 있지만 다시 시작한 후에는 것이다 때때로 에뮬레이터를 다시 시작

error_reporting(E_ALL); // in case its turned off and your not seeing errors 

ini_set('display_errors','1'); // confirm and browse to page 

if($base) { 
    $ttime = intval(time()); 
    $quality = '100'; 
    $save_to = 'images/img-' . $ttime . '.jpeg'; 
    $binary=base64_decode($base); 
    $im = imagecreatefromstring($binary); 
    if ($im !== false) { 
     header('Content-Type: image/jpg'); 
     $idno = ImageJPEG($im, $save_to, $quality); 
     imagedestroy($im); 
     echo "iid:" . $ttime; 
    } else { 
     echo "Error:" . $ttime; 
    } 
} 
관련 문제