将图像从android上传到php服务器

时间:2011-07-29 08:05:12

标签: php android upload image

我正在尝试将照片从Android设备上传到php网站。 为此,我使用MultipartEntity编码。

对于added external jar file我的项目我httpmime-4.1-beta1.jar

我要上传到php网站的内容是image上存储的SDcard。 为此,我在我的代码中执行以下操作:

HttpPost httppost = new HttpPost("....the link to the webiste...");

        MultipartEntity reqEntity = new MultipartEntity();
        StringBody sb=new StringBody("....");


        File file=new File("/sdcard/image.jpg");
        FileBody bin = new FileBody(file);
        reqEntity.addPart("android",bin);
        reqEntity.addPart("id", sb);

        httppost.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();


       if (resEntity != null) {
            String page = EntityUtils.toString(resEntity);
            System.out.println("PAGE :" + page);
        }

但问题是来自php服务器的响应始终是一个断开的链接。

我接下来要尝试的是使用

 MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

但不幸的是,我导入的jar没有HttpMultipartMode.BROWSER_COMPATIBLE的类。所以如果你能指出我正确的方向,我真的很感激 - 我还应该为此工作输入什么....或者我应该如何将图像上传到服务器。 我必须说服务器是以这种方式上传照片的构建:

method="post" enctype="multipart/form-data"
                      name="form" target="_self" id="form">
                    <input type="hidden" name="p" value="a" />

谢谢!

1 个答案:

答案 0 :(得分:2)

我建议不要使用beta库。您应该使用apache-mime4j-0.6

您还需要httpmime-4.0.1

这些必须是你的进口:

      import org.apache.http.HttpResponse;
      import org.apache.http.client.ClientProtocolException;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.entity.UrlEncodedFormEntity;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.entity.mime.HttpMultipartMode;
      import org.apache.http.entity.mime.MultipartEntity;
      import org.apache.http.entity.mime.content.FileBody;
      import org.apache.http.entity.mime.content.StringBody;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.apache.http.message.BasicNameValuePair;