Home

Saturday, March 20, 2010

Uploading Multipart Image

 

After a long struggle I found a way to upload an image in a multipart method using POST. For this, it is required to use the apache’s jar file rather than using the Android’s native HTTP apis. This makes the process simple.

Before going to the code, its is required to download the required jar files.

http://www.java2s.com/Code/JavaDownload/PostMethodExample.zip

The above source code bundle has the required jar files in its lib directory. You need to add this in to your android project’s lib directory and use the following code.

 

static boolean doUploadinBackground(final byte[] imageData) throws Exception{
        String responseString = null;
        PostMethod method;

        method = new PostMethod(Constants.hostAddress+Constants.imgUploader);

                org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(
                                100000);

                FilePart photo = new FilePart("photoData", new ByteArrayPartSource(
                        "photoData", imageData));

                photo.setContentType("image/jpeg");
                photo.setCharSet(null);
                String s    =   new String(imageData);
               Part[] parts = {
                                new StringPart("mobileNo", “12345”),
                                photo
                                };

                method.setRequestEntity(new MultipartRequestEntity(parts, method
                                .getParams()));

                client.executeMethod(method);
                responseString = method.getResponseBodyAsString();
                method.releaseConnection();

                Log.e("httpPost", "Response status: " + responseString);

        if (responseString.equals("SUCCESS")) {
                return true;
        } else {
                return false;
        }
    }

 

I hope this helps you. If you have any doubts, please email me at rames.p@gmail.com

No comments:

Post a Comment