10

As part of my Android app, I'd like to upload bitmaps to be remotely stored. I have simple HTTP GET and POST communication working perfectly, but documentation on how to do a multipart POST seems to be as rare as unicorns.

Furthermore, I'd like to transmit the image directly from memory, instead of working with a file. In the example code below, I'm getting a byte array from a file to be used later on with HttpClient and MultipartEntity.

    File input = new File("climb.jpg");
    byte[] data = new byte[(int)input.length()];
    FileInputStream fis = new FileInputStream(input);
    fis.read(data);

    ByteArrayPartSource baps = new ByteArrayPartSource(input.getName(), data);

This all seems fairly clear to me, except that I can't for the life of me find out where to get this ByteArrayPartSource. I have linked to the httpclient and httpmime JAR files, but no dice. I hear that the package structure changed drastically between HttpClient 3.x and 4.x.

Is anyone using this ByteArrayPartSource in Android, and how did they import it?

After digging around in the documentation and scouring the Internet, I came up with something that fit my needs. To make a multipart request such as a form POST, the following code did the trick for me:

    File input = new File("climb.jpg");

    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:3000/routes");
    MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    String line;

    multi.addPart("name", new StringBody("test"));
    multi.addPart("grade", new StringBody("test"));
    multi.addPart("quality", new StringBody("test"));
    multi.addPart("latitude", new StringBody("40.74"));
    multi.addPart("longitude", new StringBody("40.74"));
    multi.addPart("photo", new FileBody(input));
    post.setEntity(multi);

    HttpResponse resp = client.execute(post);

The HTTPMultipartMode.BROWSER_COMPATIBLE bit is very important. Thanks to Radomir's blog on this one.

zchtodd
  • 1,120
  • 10
  • 23
  • If anyone is looking to resolve the MultipartEntity import. Check out this blog post with links to the jar's http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/ – Blundell Nov 17 '10 at 20:43
  • 1
    Thanks for that. I was having the same problem. Except now what worries me is that the file size of my App is 3 or 4 time bigger. I wonder if there could be a way to simply add support for multipart instead of loading 4 jars. – Loïc Faure-Lacroix Dec 10 '10 at 16:08

3 Answers3

2

try this:

 HttpClient httpClient = new DefaultHttpClient() ;

 HttpPost httpPost = new HttpPost("http://example.com");
 MultipartEntity entity = new MultipartEntity();     
 entity.addPart("file", new FileBody(file));
 httpPost.setEntity(entity );
 HttpResponse response = null;

 try {
     response = httpClient.execute(httpPost);
 } catch (ClientProtocolException e) {
     Log.e("ClientProtocolException : "+e, e.getMessage());         
 } catch (IOException e) {
     Log.e("IOException : "+e, e.getMessage());

 } 
nont
  • 8,804
  • 6
  • 59
  • 78
  • 1
    Please note that MultipartEntity is not included the Android API. See this answer for a way to get the appropriate classes: http://stackoverflow.com/a/5220954/28688 – dermatthias Jun 05 '12 at 09:41
1

Perhaps you can do following step to import library into your Android.

requirement library - apache-mime4j-0.6.jar - httpmime-4.0.1.jar

  1. Right click your project and click properties
  2. select java build path
  3. select tab called "Order and Export"
  4. Apply it
  5. Fully uninstall you apk file with the adb uninstall due to existing apk not cater for new library
  6. install again your apk
  7. run it

Thanks,

Jenz

Marko
  • 19,347
  • 13
  • 45
  • 61
0

I'm having the same problem. I'm trying to upload an image through MultiPart Entity and it seens that the several updates on HttpClient/MIME are cracking everything. I'm trying the following code, falling with an Error "NoClassDefFoundError":

public static void executeMultipartPost(File image, ArrayList<Cookie> cookies, String myUrlToPost) {
    try {
        // my post instance
        HttpPost httppost = new HttpPost(myUrlToPost);
        // setting cookies for the connection session
        if (cookies != null && cookies.size() > 0) {
            String cookieString = "";
            for (int i=0; i<cookies.size(); ++i) {
                cookieString += cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
            }
            cookieString += "domain=" + BaseUrl + "; " + "path=/";
            httppost.addHeader("Cookie", cookieString);
        }
        // creating the http client
        HttpClient httpclient = new DefaultHttpClient();
        // creating the multientity part [ERROR OCCURS IN THIS BELLOW LINE]
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("photoupload", new FileBody(image));
        httppost.setEntity(multipartEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
    } catch (Exception e) {}
}

This method is fully compilable and uses the httpclient-4.0.1.jar and httpmime-4.2.jar libs, but again, I remember that it crashs in the commented line for me.

alkber
  • 1,334
  • 15
  • 26
Marcelo
  • 1,965
  • 5
  • 20
  • 36