2012-03-05 23 views
5

Básicamente, estoy intentando subir imágenes desde Android y subirlas al servidor php, pero aquí no estoy recibiendo ninguna conexión con este código o carga de imágenes
. Recibo este error.Cómo subir imágenes al servidor Php y almacenarlas en phpmyadmin

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

pero según mi conocimiento he dado la conexión correcta y el archivo php también en el dominio correcto. mirada en mi código: 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; 
    } 

}

código 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……';?> 

Cualquiera conoce este problema? si alguien sabe cómo almacenar en la base de datos MySQL desde un archivo php y viceversa traiga por favor me sugieren aquí ...

+1

Si está probando el emulador, Una vez que reinicie el emulador a veces se está dando esta excepción, pero después de reiniciar lo hará trabajar bien. También puede verificar la conexión a Internet abriendo el navegador incorporado del emulador. – Dharmendra

Respuesta

8

El problema es muy claro ...

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

significa que el HttpPost no se puede hacer una conexión utilizando el nombre de host que suministró, porque el nombre de host que proporcionó no se conoce.

Si se toma el nombre de host de esta línea:

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

y lo puso en un navegador en el mismo dispositivo que pasa ... le sugiero que obtendrá un error diciendo que no puede conectar con el anfitrión. Si esto funciona, entonces le sugiero que consulte la siguiente línea se encuentra en su manifiesto:

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

También asegúrese de que el archivo PHP contiene la siguiente cabecera si el uso de un JPEG:

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

obtengo el eco correcto cuando uso esta línea en el navegador y ahora, en la actualidad, obtengo la longitud del contenido = -1 ... ¿puede ver y n wat para hacer lo siguiente ...? – Rizvan

1

Check y elige el encabezado derecho para subir el archivo. En su código php, ha dado un tipo de encabezado incorrecto.

1

Te recomiendo que, como dijo ManseUK, añadas el permiso en tu Manifiesto. Este error es bastante clara, pero a menudo se resuelve mediante la adición de <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

Esto funciona para mí:

// cambiar el formato de compresión de mapa de bits a JPEG
bitmap.compress (Bitmap.CompressFormat.JPEG, 100, baos);

// entonces uploadimage.php

// NOTA La función de imagecreatefromstring()

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; 
    } 
} 
Cuestiones relacionadas