1

此示例适用于其中一个或另一个,但不能同时适用:

public void postData() {  
    //http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/
    File f = new File(filename);
    try {
             HttpClient client = new DefaultHttpClient();  
             String postURL = "http://url.com/script.php";


             HttpPost post = new HttpPost(postURL); 
    //         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
      //       nameValuePairs.add(new BasicNameValuePair("project", projectName));  
        //     nameValuePairs.add(new BasicNameValuePair("name", imageName));  
          //   post.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

             FileBody bin = new FileBody(f);
             MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
             reqEntity.addPart("file", bin);

             post.setEntity(reqEntity); 

             HttpResponse response = client.execute(post);  
             HttpEntity resEntity = response.getEntity();  
             if (resEntity != null) {    
                       Log.i("RESPONSE",EntityUtils.toString(resEntity));
                 }
    } catch (Exception e) {
        e.printStackTrace();
    }


}

似乎当我调用 时setEntity(),前一个实体被覆盖了——所以我可以有名称值对或文件数据,但不能同时拥有两者。你知道如何整合它们,以便我可以在上传中使用 URL 参数吗?简单地将它们附加到 POST URL 是行不通的。

我也试过

  post.addHeader("project", projectName);
  post.addHeader("name", imageName);                 

但这似乎也不起作用。

谢谢。

4

1 回答 1

4

这似乎可以解决问题:

             reqEntity.addPart("project", new StringBody(projectName));
             reqEntity.addPart("name", new StringBody(imageName));
于 2011-03-01T06:03:08.793 回答