如何将图像上传到Php服务器并存储在phpmyadmin中

如何将图像上传到Php服务器并存储在phpmyadmin中,php,android,mysql,Php,Android,Mysql,我基本上是在尝试从android上传图像并将其上传到php服务器,但在这里,我没有获得与此代码或图像上传的任何连接。 我得到了这个错误 Error in http connection java.net.UnknownHostException: host name 但据我所知,我给出了正确的连接,php文件也在正确的域中。 看看我的代码: UploadImage.java public class UploadImage extends Activity { InputStream inpu

我基本上是在尝试从android上传图像并将其上传到php服务器,但在这里,我没有获得与此代码或图像上传的任何连接
。 我得到了这个错误

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;
    }
公共类上载映像扩展活动{
输入流输入流;
@凌驾
创建公共空间(捆绑冰柱){
超级冰柱;
setContentView(R.layout.main);
位图Bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.icon);
ByteArrayOutputStream=新建ByteArrayOutputStream();
compress(bitmap.CompressFormat.PNG,90,stream);//压缩为所需格式。
byte[]byte_arr=stream.toByteArray();
字符串image\u str=Base64.encodeBytes(byte\u arr);
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“image”,image_str));
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://server.com/uploadimage/uploadimage.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
字符串\u字符串\u响应=convertResponseToString(响应);
Toast.makeText(UploadImage.this,“Response”+字符串响应Toast.LENGTH.LONG.show();
}捕获(例外e){
Toast.makeText(UploadImage.this,“ERROR”+e.getMessage(),Toast.LENGTH\u LONG.show();
System.out.println(“http连接中的错误”+e.toString());
}
}
公共字符串convertResponseToString(HttpResponse响应)引发IllegalStateException,IOException{
字符串res=“”;
StringBuffer=新的StringBuffer();
inputStream=response.getEntity().getContent();
int contentLength=(int)response.getEntity().getContentLength();//获取内容长度…。。
Toast.makeText(UploadImage.this,“contentLength:+contentLength,Toast.LENGTH_LONG).show();
if(contentLength<0){
}
否则{
字节[]数据=新字节[512];
int len=0;
尝试
{
而(-1!=(len=inputStream.read(data)))
{
append(新字符串(数据,0,len));//转换为字符串并追加到stringbuffer…。。
}
}
捕获(IOE异常)
{
e、 printStackTrace();
}
尝试
{
inputStream.close();//关闭流…。。
}
捕获(IOE异常)
{
e、 printStackTrace();
}
res=buffer.toString();//正在将stringbuffer转换为字符串…。。
Toast.makeText(UploadImage.this,“结果:+res,Toast.LENGTH_LONG).show();
//System.out.println(“Response=>”+EntityUtils.toString(Response.getEntity());
}
返回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
无法使用您提供的主机名进行连接-因为您提供的主机名未知

如果从此行获取主机名:

HttpPost httppost = new HttpPost("http://server.com/uploadimage/uploadimage.php");
把它放在同一台设备上的浏览器里会发生什么。。。我建议您将得到一个错误,说无法连接到主机。如果这样做有效,我建议您检查清单中的以下行:

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

检查主机配置并为文件上载选择正确的标头。在php代码中,您给出了错误的头类型。

正如ManseUK所说,我建议您在清单中添加权限。 此错误非常不清楚,但通常通过添加

1来解决。需要在android清单文件中添加Internet权限。
2.每次我都会使用url查看图像,但由于没有添加,所以无法查看
回声“;
3.$file=fopen('test.jpg','wb');
4.最后一件事是我必须将头文件更改为:
标题('Content-Type:image/jpg;charset=utf-8');
这对我很有用:

//将位图压缩格式更改为jpeg
压缩(bitmap.CompressFormat.JPEG,100,baos)

//然后上传image.php

//注意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;  
    }  
}  

如果您在emulator上进行测试,一旦重新启动emulator,它有时会出现此异常,但在重新启动后,它会正常工作。你也可以通过打开模拟器的内置浏览器来检查互联网连接。当我在浏览器中使用这一行时,我得到了正确的回音,现在得到的内容长度=-1。。你能看看下一步怎么办吗。。
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');
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;  
    }  
}