Saturday, May 4, 2013

[Android Tips]: Uploading Images to a Remote Web Service

upload

In order to upload images to a web service that requires a Multipart request, the below code will create the file part object and include it as part of the MultiPartRequest entity. I store this method in a separate class and call it statically from within an AsyncTask.  This type of functionality is particularly useful for when you want to upload a user's profile photo and store it on your remote file system.

The following Apache libraries are required:

  • commons-codec.jar (version used: 1.3)

  • commons-httpclient.jar (version used: 3.0-rc4)

  • commons-logging.jar


[code language="java"]
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

static boolean doImageUpload(final byte[] imageData, String fileName) throws Exception {
String responseString = null;

PostMethod method = new PostMethod(<remote url>);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(100000);

FilePart photo = new FilePart("file-data", new ByteArrayPartSource(fileName, imageData));
photo.setContentType("image/jpeg");
photo.setCharSet(null);

Part[] parts = {photo};
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
client.executeMethod(method);

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

if (responseString.equals(<successful response>)) {
return true;
} else {
return false;
}
}
[/code]

Have you done this a different way?  Leave a comment below.

*** Download our first game: Word Crank today for free: Available on iOS and Android***