Wednesday, April 2, 2014

Upload an image from Android to Google's app engine server

Recently I have started working on a project on Android. This app involves uploading few images chosen by user to the server. App engine has a document page at https://developers.google.com/appengine/docs/java/blobstore/, but unfortunately for Android developer it is not enough. This document mentions how to upload using web client i.e. using using form in a html page.

For uploading using java application we need a multipart message. We need following libs:
1. httpcore-4.3.2.jar
2. httpmime-4.3.3.jar

httpcore-4.3.2.jar and httpmime-4.3.3.jar can be found at http://hc.apache.org/downloads.cgi.These jars are part of zip file containing other files. Extract the entire zip and copy these two required files in <android project>/libs.

public void uploadBlobImage( String path, String link ) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(link);

        try {
            MultipartEntity entity = new MultipartEntity();
            entity.addPart("type", new StringBody("photo"));
            File file = new File( path );
            entity.addPart("data", new FileBody(file, ContentType.create( "image/jpg"),"Swapnil.jpg"));
            
            httppost.setEntity(entity);
            HttpResponse response = httpclient.execute(httppost);
            Log.d( Utils.AppName, "Image uploaded: "+ response.toString( ));
        } catch (Exception e) {
            Log.d( Utils.AppName, "Image not uploaded: Exception:"+ e.toString( ));
        }        
    }
Note

In my first draft of this post the code for new file body was:
new FileBody(file, ContentType.create( "image/jpg")/*,"Swapnil.jpg" */)
For some strange reason this did not work and upload used to fail. Please let me know if you know the reason.

Android aar deployment in Maven - 2022

Introduction If you are working on android library project, you might be wondering how to publish it on Maven like this . Earl...