2

I am trying to upload an image from an Adroid app to a php webserver using HttpClient and MultipartEntity.

Here is a snippet of my code :

protected Void doInBackground(Void... params) {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost post = new HttpPost( "http://URL/upload.php" );

    try {
        MultipartEntity entity = new MultipartEntity(  );
        entity.addPart("type", new StringBody("photo"));
        entity.addPart("data", new FileBody(new File (this.path)));         
        post.setEntity(entity);
        post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);             
        post.addHeader( "Content-Type", "multipart/form-data; ");

        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();

        System.out.println(response.getStatusLine());

        client.getConnectionManager().shutdown();
    } catch (UnsupportedEncodingException e) {          
        e.printStackTrace();
    } catch (ClientProtocolException e) {           
        e.printStackTrace();
    } catch (IOException e) {           
        e.printStackTrace();
    }

    return null;
}

in the php file I've added print_r($_FILE) to see the content of the Array, and it's showing an empty array.

LogCat is showing the following after executing the HttpClient

06-17 14:54:03.908: I/System.out(1256): HTTP/1.1 200 OK
06-17 14:54:03.998: D/111(1256): Array
06-17 14:54:03.998: D/111(1256): (
06-17 14:54:03.998: D/111(1256): )
06-17 14:54:04.068: D/dalvikvm(1256): GC_CONCURRENT freed 200K, 12% free 2559K/2900K, paused 96ms+5ms, total 161ms

Can anybody tell me what I have to add to the Android code ?

user2478861
  • 63
  • 2
  • 5
  • Which code do you receive in your HttpResponse afer client.execute? Would be helpful. – zozelfelfo Jun 17 '13 at 14:50
  • Here is the LogCat showing informations `06-17 14:54:03.908: I/System.out(1256): HTTP/1.1 200 OK 06-17 14:54:03.998: D/111(1256): Array 06-17 14:54:03.998: D/111(1256): ( 06-17 14:54:03.998: D/111(1256): ) 06-17 14:54:04.068: D/dalvikvm(1256): GC_CONCURRENT freed 200K, 12% free 2559K/2900K, paused 96ms+5ms, total 161ms` – user2478861 Jun 17 '13 at 14:55

2 Answers2

0

Per a blog post about using MultipartEntity to post data to a url, you may need to include some additional jar files in your project. They include the following apache open-source projects: apache-mime4j, httpclient, httpcore and httpmime.

SBerg413
  • 14,515
  • 6
  • 62
  • 88
0

Add this in your constructor:

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
hichris123
  • 10,145
  • 15
  • 56
  • 70
TuGordoBello
  • 4,350
  • 9
  • 52
  • 78