Android: Upload image or file using http POST multi-part


Hi,

After spending whole day, I thought that I should post my experience.

I’m trying to upload image to my server using Android 1.5 SDK.

By using this method,  you will be able to upload a file from your SD Card and also Bitmap image as a file.

Prerequisite: httpmime-4.1-beta1.jar

Android SDK uses apache  http Client of version 3.0. That does not support for the mime type.

So download the latest HttpClient from here. (Go to latest i.e. HttpClient 4.1-Beta1, and download zip file from Binary with dependencies)

Now include the above jar file as an external jar file.

Now create a new project and update your code from following:

package com.isummation.fileupload;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

public class FileUpload extends Activity {
	Bitmap bm;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			// bm = BitmapFactory.decodeResource(getResources(),
			// R.drawable.forest);
			bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
			executeMultipartPost();
		} catch (Exception e) {
			Log.e(e.getClass().getName(), e.getMessage());
		}
	}

	public void executeMultipartPost() throws Exception {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bm.compress(CompressFormat.JPEG, 75, bos);
			byte[] data = bos.toByteArray();
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(
					"http://10.0.2.2/cfc/iphoneWebservice.cfc?returnformat=json&method=testUpload");
			ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
			// File file= new File("/mnt/sdcard/forest.png");
			// FileBody bin = new FileBody(file);
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			reqEntity.addPart("uploaded", bab);
			reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
			postRequest.setEntity(reqEntity);
			HttpResponse response = httpClient.execute(postRequest);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse;
			StringBuilder s = new StringBuilder();

			while ((sResponse = reader.readLine()) != null) {
				s = s.append(sResponse);
			}
			System.out.println("Response: " + s);
		} catch (Exception e) {
			// handle exception here
			Log.e(e.getClass().getName(), e.getMessage());
		}
	}
}

Modify web service URL to match yours.

Also note that I commented some lines in executeMultipartPost() method. This is used to read a file from SD card, then pass this bin object in reqEntity.addPart() method to upload any file.

FYI: png formatted file and Bitmap images are too big. So I compress it to JPEG format while uploading.

See the line:

bm.compress(CompressFormat.JPEG, 75, bos);

This is very important, because it can convert a 1.8 MB file to 180 KB!.

PS: In example, I’m using ColdFusion component (cfc) as a Restful service with JSON as return format. This is the easiest way to implement your server part. I am also using Android 1.5 SDK, because I believe that your application should be compatible with all ( varying from 1.5 to 2.3) SDK versions!.

Hope that this post helps you…

You might also like: https://vikaskanani.wordpress.com/2011/01/29/android-image-upload-activity/