Android: Image upload activity


After working on how to upload image, I decided to post complete activity code, and that will help for new Android developers.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
	android:layout_width="fill_parent" android:layout_height="fill_parent">
 <ImageView android:id="@+id/ImageView" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:layout_centerInParent="true" />
 <Button android:layout_width="wrap_content" android:id="@+id/Upload"
		android:layout_height="wrap_content" android:layout_alignParentLeft="true"
		android:layout_alignParentBottom="true" android:text="Upload" />
 <EditText android:id="@+id/Caption" android:layout_width="500px"
		android:layout_height="wrap_content" android:hint="Write caption"
		android:singleLine="true" android:layout_toRightOf="@id/Upload"
		android:layout_alignParentBottom="true" />

package com.isummation.imageupload;


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 org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;

import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageUpload extends Activity {
	private static final int PICK_IMAGE = 1;
	private ImageView imgView;
	private Button upload;
	private EditText caption;
	private Bitmap bitmap;
	private ProgressDialog dialog;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {

		imgView = (ImageView) findViewById(;
		upload = (Button) findViewById(;
		caption = (EditText) findViewById(;
		upload.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (bitmap == null) {
							"Please select image", Toast.LENGTH_SHORT).show();
				} else {
					dialog =, "Uploading",
							"Please wait...", true);
					new ImageUploadTask().execute();


	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(, menu);
		return true;

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
			try {
				Intent intent = new Intent();
						Intent.createChooser(intent, "Select Picture"),
			} catch (Exception e) {
				Log.e(e.getClass().getName(), e.getMessage(), e);
			return true;
			return super.onOptionsItemSelected(item);

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PICK_IMAGE:
			if (resultCode == Activity.RESULT_OK) {
				Uri selectedImageUri = data.getData();
				String filePath = null;

				try {
					// OI FILE Manager
					String filemanagerstring = selectedImageUri.getPath();

					String selectedImagePath = getPath(selectedImageUri);

					if (selectedImagePath != null) {
						filePath = selectedImagePath;
					} else if (filemanagerstring != null) {
						filePath = filemanagerstring;
					} else {
						Toast.makeText(getApplicationContext(), "Unknown path",
						Log.e("Bitmap", "Unknown path");

					if (filePath != null) {
					} else {
						bitmap = null;
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Internal error",
					Log.e(e.getClass().getName(), e.getMessage(), e);

	class ImageUploadTask extends AsyncTask <Void, Void, String>{
		protected String doInBackground(Void... unsued) {
			try {
				HttpClient httpClient = new DefaultHttpClient();
				HttpContext localContext = new BasicHttpContext();
				HttpPost httpPost = new HttpPost(
								+ "/cfc/iphonewebservice.cfc?method=uploadPhoto");

				MultipartEntity entity = new MultipartEntity(

				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 100, bos);
				byte[] data = bos.toByteArray();
				entity.addPart("photoId", new StringBody(getIntent()
				entity.addPart("returnformat", new StringBody("json"));
				entity.addPart("uploaded", new ByteArrayBody(data,
				entity.addPart("photoCaption", new StringBody(caption.getText()
				HttpResponse response = httpClient.execute(httpPost,
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								response.getEntity().getContent(), "UTF-8"));

				String sResponse = reader.readLine();
				return sResponse;
			} catch (Exception e) {
				if (dialog.isShowing())
				Log.e(e.getClass().getName(), e.getMessage(), e);
				return null;

			// (null);

		protected void onProgressUpdate(Void... unsued) {


		protected void onPostExecute(String sResponse) {
			try {
				if (dialog.isShowing())

				if (sResponse != null) {
					JSONObject JResponse = new JSONObject(sResponse);
					int success = JResponse.getInt("SUCCESS");
					String message = JResponse.getString("MESSAGE");
					if (success == 0) {
						Toast.makeText(getApplicationContext(), message,
					} else {
								"Photo uploaded successfully",
			} catch (Exception e) {
				Log.e(e.getClass().getName(), e.getMessage(), e);

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		if (cursor != null) {
			int column_index = cursor
			return cursor.getString(column_index);
		} else
			return null;

	public void decodeFile(String filePath) {
		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, o);

		// The new size we want to scale to
		final int REQUIRED_SIZE = 1024;

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp &lt; REQUIRED_SIZE &amp;&amp; height_tmp &lt; REQUIRED_SIZE)
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;

		// Decode with inSampleSize
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;
		bitmap = BitmapFactory.decodeFile(filePath, o2);




<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="">
	<item android:id="@+id/ic_menu_gallery" android:icon="@drawable/ic_menu_gallery"
		android:title="Gallery" />

Tips: To upload a camera picture, we can directly call camera activity. But it may return you a small, thumbnail sized image. So while browsing the gallery we can also take a new picture, and then we select that picture to upload.

Remember that my decodeFile() function will reduce the size of image, when we convert it to bitmap to show selected image. It is important because a large size of image can crash your application. Think that you load 8 Mega pixel image with 5 MB size into RAM of Android mobile! It definitely crash the application.

Also If you want to upload the full sized image then, just use the filePath. Instead of using ByteArrayBody(), use the following line:

entity.addPart("uploaded", new FileBody(new File(filepath)));

Again, if you upload a large size of image with slow Internet speed, it will take long long time. So just limit it size and also choose the compress format for the image.


ColdFusion function to receive file:

<cffunction name="uploadPhoto" access="remote" output="false" returntype="struct">
		<cfargument name="photoId" required="true" type="numeric" />
		<cfargument name="photoCaption" required="false" type="string" default=""/>
		<!--- Receive File --->
		<cfargument name="uploaded" required="true" type="any" />

		<!--- Save file --->
		<cfset Variables.Path="/upload"/>
		<cfset Variables.FolderPath="#Expandpath(Variables.Path)#" />
		<cffile action="upload"

		<!--- Other code --->
		<cfreturn retStruct>


Download source code: Download


200 thoughts on “Android: Image upload activity

  1. Hi vikas,
    thanks for your blog posts. it is very useful to learn new things while developing android apps.
    I need some guide lines from you for developing an app.i hope you can help me.
    I am developing an android app which can record a video and post that video file to a server (ex :– using httppost method.
    how can i get recorded video file format to send as file name?
    how can i do this ? please help me in this.

    thanks in advance

      1. I think this requirement is quite vague. Can I access another’s gmail ID? or how to upload photo and publish it into picasa…I am interested in second, . I’ll definitely come up with second one.

      2. Thanks,Its good example,When we use Multipart do we need to download any jar files.If possible could you post any code for uploading zip files

      3. Yes, download the jar files mentioned in my previous code. If you look at my previous post, you’ll see a code where I commented some line. That can be used to upload any file to server.

  2. Hi,

    This is a very good and beneficial tutorial. I would like to point one thing to you that the code is not showing up and the end of lines are cut and not completely visible. I am using Firefox on Vista.

    Can you please put this code in a zip format for download or can you resolve this cut off issue. Thanks.

      1. ya , i too face the same problem, there is no image on display on the emulator, if i press the upload button, it just gives a toast message “please select image”, how to resolve this?..pls help

    1. Click on the menu button on the right hand side of emulator and it will open up the gallery for you to choose an image.

  3. I have problems:

    Description Resource Path Location Type
    The method doInBackground(Void…) of type phocha.phochaTask must override a superclass method /phocha/src/are/phocha line 149 Java Problem
    The method onPostExecute(String) of type phocha.phochaTask must override a superclass method /phocha/src/are/phocha line 197 Java Problem
    The method onProgressUpdate(Void…) of type phocha.phochaTask must override a superclass method /phocha/src/are/phocha line 192 Java Problem

      1. hi
        i remove the Async task and upload function its working but i am working android studio if run the file means it showing this Error: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType i import httpclient,httpcore,httpmime jar file also wat can i do now please help me out…..urgent

  4. Hi Vikas,

    can you plz mail me the manifest file for the same program.
    and please explein where to store which code file.
    for refrence: imageupload_menu.xml will b stored in layout directive.

    early response will b appreciated.

    thanks in adv

  5. Hi shivam

    I’ve same problem with Are

    “Description Resource Path Location Type
    The method doInBackground(Void…) of type phocha.phochaTask must override a superclass method /phocha/src/are/phocha line 149 Java Problem
    The method onPostExecute(String) of type phocha.phochaTask must override a superclass method /phocha/src/are/phocha line 197 Java Problem
    The method onProgressUpdate(Void…) of type phocha.phochaTask must override a superclass method /phocha/src/are/phocha line 192 Java Problem”

  6. @onDoi and @shivam, Async task is just to show busy activity, you can remove that Async task and just merge the code of doInBackground() & onPostExecute() and place them where I call it i.e. new ImageUploadTask().execute()

  7. Hi Vikas
    I still have problem with Async. I changed Async to Async and the error is gone but it doesn’t work. It stop on this line String sResponse = reader.readLine();

    and I try to do by just copy code in doInBackground() & onPostExecute() to place the call it, agian it doesn’t work
    error at entity.addpart . Can you send me your project to me?
    Thank you for your advice.

    1. Unfortunately, I don’t have source code. But as you said that you get an error in entity.addpart(), I reviewed my code and saw that I am not using following line.
      entity.addPart(“photoId”, new StringBody(getIntent().getStringExtra(“photoId”)));

      So remove that line, then It should work.

  8. “To upload a camera picture, we can directly call camera activity. But it may return you a small, thumbnail sized image. So while browsing the gallery we can also take a new picture, and then we select that picture to upload.”

    I see what you are saying. The question I have is: can we open the camera automatically when we start the select picture intent? And I don’t mean use the camera activity — I mean do it how you have in the example, but add perhaps an intent extra to bypass the gallery and boot the camera but using the gallery intent so we get the full size images?

    Make sense?

  9. I am trying to integrate some of this into my exisitng app, this is becoming a challenge. Just an FYI, you may want to put at the top about the menu file going in res/menu, you may also want to mention the 2 edits to vales/strings.xml

  10. Ok, integrating isn’t working to well, maybe you can give me a hand? I have a webview and i want to add the upload button to the bottom, when clicked i want it to change screens to the upload form, when done change back to my webview. Any help would be appreciated

  11. Since i cant edit, i have to keep posting, i am not a Cold Fusion guy, i am a PHP guy, and chance of some PHP code ideas without JSON?

      1. Can you correct me the c# handler code ??
        It does not throw any errors, but the adroid application stops,
        saying “FORCE CLOSE” as it has stopped unexpectedly.
        What do I do now ?

        I hav followd your directions, but I hav not been successful.

        THis is my handler:

        public class MapHandler : IHttpHandler
        public void ProcessRequest(HttpContext context) {
        HttpPostedFile oFile = context.Request.Files[“Filedata”];

        if (oFile != null) {
        const string sDirectory = “c:\\Neuer Ordner”;
        if (!System.IO.Directory.Exists(sDirectory))

        oFile.SaveAs(System.IO.Path.Combine(sDirectory, oFile.FileName));

        else {
        public bool IsReusable {
        get {
        return false;

  12. That is fine, i will work out the PHP stuff and give you the codes to post here. For now, any help with my other message?

  13. Ok, so i got it working but i am using your getPath function, and it seems to work most of the time. It did however give a null pointer error when selecting a gif. Is there a workaround to use more than just a JPG?

    1. I’ve updated post with providing source code. And for gif image, you can also upload it, use OI file manager and then select gif file from your card and upload it. I got working it.

      1. Thanks, i have applied your small change and added some of your decode function, it seems a bit better than my compression routine.

  14. I am Just learn to write basic android.
    Help me with.
    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;

  15. Hi vikas…..i have used ur code but…am getting errors for MultipartEntity and stringbody……do i need to add any external jars for that?

      1. Great tutorial! Thank you so much!
        I already include extra Http Mime library (httpmime-4.3-beta2.jar) into my build path, but i get the following error when i uploading an image from the app:

        Could not find class ‘org.apache.http.entity.mime.MultipartEntity’, referenced from method com.example.uploadimage.ImageUpload$ImageUploadTask.doInBackground

        Do you know how to solve this problem?

  16. Great example thanks. Rather than using coldfusion will this code work with php, specifically post. Currently I use a php and upload the image data as a base 64 string, get the data from the post and decode. However, I am running into problems is the image size is too big.


  17. i m getting error in
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    how to solve this error?

  18. i am getting the problem while uploading process. Image is being displayed and then clicking on the upload button i can see only the dialog for “Uploading”

  19. Hi Vikas,
    This bolg helped me a lot. However, The application is running in emulator perfectly. when i load this to phone, it giving the application has stopped unexpectedly. Please try again.

    Is there any thing need to be set in my phone. I am able to send some text data to my server file through http post( means APN is set correctly). Some where i lost to find out why it is failing in phone.

  20. please, help me .. .
    I use your code but it can’t work
    follow is my code

    package file.up.load;

    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import java.util.Date;
    import android.os.Bundle;

    public class fileup extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

    final TextView tmp = (TextView) findViewById(;
    tmp.setText(“Hi! Click the button!”);

    Button b = (Button) findViewById(;
    b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    File f = new File(“/sdcard/test.txt”);
    try {
    Date d = new Date();
    PrintWriter writer = new PrintWriter(f);
    HttpClient client = new DefaultHttpClient();
    httpPostFileUpload(client, “/sdcard/test.txt”, “http://localhost/upload.php”, “uploadedfile”);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    public void httpPostFileUpload(
    HttpClient client,
    String filePath,
    String uploadUri,
    String inputNameAttr) throws ClientProtocolException,
    IOException {
    HttpUriRequest request = new HttpPost(uploadUri);
    MultipartEntity form = new MultipartEntity();

    client.getParams().setBooleanParameter(“http.protocol.expect-continue”, false);
    form.addPart(inputNameAttr, new FileBody(new File(filePath)));
    ((HttpEntityEnclosingRequestBase) request).setEntity(form);
    try {
    } catch (ClientProtocolException e) {
    throw e;
    } catch (IOException ee) {
    throw ee;

    it error at
    form.addPart(inputNameAttr, new FileBody(new File(filePath)));

    what should I do, the path is incomplete …
    I don’t understand

      1. Vikas, thank a lot for you help, but it can’t work.
        Do you have any code to upload and download text file in sdcard to web server (php) ? Help me plese.

      2. Well for that, we may need extra logic to convert text file to byte array, try that, I’ll also try this in future.

  21. hiiiiiiiiii
    vikash .i m feashing one problem.i wnt upload the image in employee form.without using drawable.s

      1. ya i m using Bitmap object.after using bitmap object one message are showing on avd. upload butoom r showing nd then edit text is showing.wt i ll write in edit text…

    1. Read a video file, convert it to byte array, but this may not be advisable as converting into byte array would take lots of memory, you may need to use buffered reader/writer with open URL connection. Check this.

  22. hiiiiiiiii
    vikas i want create XYchart in android .i have one form in side form have income and expenses so i want show the both value in XYchart………..

  23. I don’t have Cold Fusion Server either on local host or on my web site. Vikas do you or anyone else know classic asp, or can anyone provide the php code that I might translate it into classic asp – so I can try this tutorial? I downloaded the zip imported it into Motodev-eclipse along with the httpmime-4.1-beta1.jar file. It compiled nicely, but alas – cf is all greek to me!! Help!!

    1. Well, I know classic asp. you just create two page, from one page just add input type file and try to send it to page 2, if get success then the same way we can implement it on android. Just go ahead with classic asp, then if needed provide code, I’ll help you.

      1. Hi Vikas . Success! I was trying to overcomplicate it. You response made everything click! I pulled out of archive an old implementation of ASPUpload that I used several years ago. If anyone is interested, I checked the web and it’s still a free download available at: Anyway, I stripped away the HTML from the form page – posted to it, and yes!! Then I went further and inserted the image into a mySQL database BLOB field. That was my ultimate goal. Thanks for your tutorial – great! The only thing I’m lacking now is sending a response back to the Phone to generate a Toast or whatever!

  24. MultipartEntity entity = new MultipartEntity(
    157 HttpMultipartMode.BROWSER_COMPATIBLE);
    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;

    doesnt recognize these imports

  25. Hi Vikas,

    First of all thanks a lot for your code. I have it working 90%. The 10% is because The photo selector is not opened but I don’t have errors on the code and I have all the files in my project.
    In fact, I have the icon, upload button and the caption box in my screen. Do you know what’s is missing? Something that I neeed to configure?

    Thx in advance.


  26. I have imported your full project and compiles perfect! But still I have the same issue. In the screen I have Upload button an the caption box. Now I have your androidmanifest.
    Debugging I have seen how the following lines onCreate function are debugged correctly but after caption line the program finished and shows the screen:

    imgView = (ImageView) findViewById(;
    upload = (Button) findViewById(;
    caption = (EditText) findViewById(;

    Which code has to show the photos browser? This line “mgView = (ImageView) findViewById(;”??

    I have istalled the apk in my phone but I see the same as the emulator…

    1. I think it is impossible or little hard. If I am using bufferwritter then I can publish the percentage, but again is it very difficult to know how much chunk of data has been transferred and how much data is successfully received on server side. This is a very good topic, I’ll work on that in free time.

  27. Hi

    I am new in the Android environment. I have copied your code and I could able to run but it has one problem. I could not get Gallery menu in my emulator. Is it need to enable anything for enable the menu?

    Binesh J M

    1. Thanks for referring my post, I am planning to re publish the code with improved and enhanced code, because I’ve never updated this post then after..

  28. Hi I used the code successfully on Android 2.1 posting to an asp file as I said on May 30, 2011.
    However, on Android 2.3.3 (Gingerbread) I get the following error:
    value < font of type Java.Lang.String cannot be converted to a JSONOBJECT

    Could you help me with this??

      1. Actually I was using your code – and in your defense it works beautifully. The problem actually was that I was passing the mobile number (Line1Number) in my url to get the right record. The original phone I was using passed a 10 digit number and second phone (set up for international use) included a “1” making it an 11 digit number. I changed my code on the server side to: Right(request.(l1num),10) – which fixed my problem.

        Hate answering my own questions – but perhaps someone else might be as slow as me! 🙂


  29. thank you for your share. i want to develop an app uploding photos to facebook, flickr, twitter etc. can i modfy these codes or i have to use different codes.

      1. hello Vikas,,
        I need your help ,, I m opening Html page using WebView in android.
        My html page has Browse button so I want that when i click on ts Browse button it selects the image from galary or sdcard and uploads its.
        Well it is possible ?? in android

  30. Great Tutorial, really helped me, but I’m using Php on the backend and the app shuts down after It try to execute the HttpPost. The ProgressDialog shows and then the app forces a shutdown. my Backend script is
    “1”, “MESSAGE”=>”Your pics have been uploaded”);

    Any ideas?

    1. Is there any connection issue? It the picture is too big? instead of using picture, try to use icon from your application. These trouble shooting may help you.

  31. Hi there.
    I get an error running the application, I managed to track where the application forces to close.

    bitmap.compress(CompressFormat.JPEG, 100, bos);

    Is compress working badly? Manifest property?

    09-26 07:55:38.565: WARN/dalvikvm(444): threadid=17: thread exiting with uncaught exception (group=0x4001aa28)
    09-26 07:55:38.625: WARN/InputManagerService(51): Window already focused, ignoring focus gain of:$Stub$Proxy@4387abf0
    09-26 07:55:38.685: ERROR/AndroidRuntime(444): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception


  32. Hi am new to Android.This doesnt work for me, there is no way to select an image or take a photo.Am using emulator 2.1…emulator screen showing upload button,when i click on button,it showing “please select image”.Can u help..

    1. Did you hit the Android “menu” key, where the option to go to the gallery and get an image is? (if using emulator, you will need images in that environment … I have been using a real device to test)

      1. Thanks for your reply David, when i clicked on menu, it showing gallery option then when i clicked on galley it showing no media found. how can i store image on gallery in the emulator window without programmatic….. i hope i will get reply asap.

      2. You can Start a camera and take a picture. I know some of the emulator cause force close when starting camera. You can also open browser and download some images from web. Third option is to put the image via DMDS option in eclipse. Once you save any image and if you don’t get it into the gallery, restart emulator. Hope that helps.

  33. Hi Vikas, the client code for multi-part uploading the image seems to be working fine. But from the server side am not able to retrieve the image, can u tell me how to extract the image in server side. Below is my client code:

    HttpPost httpPost = new HttpPost(new URI(url));
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    // uploading image here
    if(mImagePath != null) {
    File file= new File(mImagePath);
    if(file.exists()) {
    reqEntity.addPart(“image”, new FileBody(file));

    Thnx in advance………

  34. Since i spent several days trying to figure out why this wasn’t working for me…

    This doesn’t work right in honeycomb initially:

    You need:
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    To allow your main thread to run network tasks. I think there is a more elgant work around to put this into its own thread or something but unfortunately i don’t have time to figure that out.

  35. Hi Vikas,
    Nice post, However it cant return picture to Emulator from sdcard .img, file.
    My question is how it can interact with Google App Engine? Do you have any idea or suggest?
    Maybe you can give me an example in hard code.
    Thank you

  36. how to add an image to twitter from android application.i have used oauth and json to post tweets.but how to add an image like twitter composer has it in the left bottom.please send me a bit of code to add images..

  37. Thanks for sharing this!

    I had been looking for a straight forward way to upload a file without having to hack the request from scratch. This is really helpful.


  38. Hi Vikas,

    Sounds you don’t know PHP, so I’m not asking you to give me a PHP code. But since I don’t know ColdFusion, can you please tell me how to use that script so that I can get it worked? Do I need special software or webserver?

  39. i used ur code in 2.3.3 it worked well on emulator but when i tested on android mobile it does not show the option for clicking new image in gallery .why its so

  40. Hi Vikas, this is really very awesome and thank you for all of this.
    well I have one thing to ask , if its multiple pictures or images, I mean if I have to choose more then one and send them to the server, how will I implement this??
    Thanks in advance

  41. this however gives me a failure response on server side
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==1 && resultCode==RESULT_OK)

    Uri imageUri=data.getData();
    final String path=imageUri.getPath();
    Log.i(“path is”, path);

    ContentResolver cr=getContentResolver();

    String [] projection={MediaStore.Images.Media.DATA,MediaStore.Images.Media.LATITUDE,MediaStore.Images.Media.LONGITUDE};
    Cursor c=cr.query(imageUri, projection, null, null, null);
    Log.i(“imgData”, imgData);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bm.compress(CompressFormat.JPEG, 100, bos);
    final byte[] imageByteArray = bos.toByteArray();

    ImageView show=(ImageView)findViewById(;
    TextView describe=(TextView)findViewById(;
    final EditText caption_des=(EditText)findViewById(;
    Button upload=(Button)findViewById(;
    upload.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
    // TODO Auto-generated method stub
    String caption=caption_des.getText().toString();
    File dir = Environment.getExternalStorageDirectory();
    String root=Environment.getExternalStorageDirectory().getAbsolutePath();

    Log.i(“abs path”, root);
    File imageToUpload =new File(“”, imgData);
    Log.i(“file”, imageToUpload.toString());

    HttpClient httpclient = new DefaultHttpClient();
    HttpContext con=new BasicHttpContext();

    //ContentBody imageFileCB = new FileBody(imageToUpload);
    //FileBody imageFileCB=new FileBody(imageToUpload);
    //Log.i(“CB”, “null”+imageFileCB.toString());

    ByteArrayBody bab = new ByteArrayBody(imageByteArray, “abc.jpg”);
    MultipartEntity entitity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    String url=””;

    HttpPost post=new HttpPost(url);

    post.setHeader(“Content-Type”, “multipart/form-data”);
    post.setHeader(“charset”, “UTF-8”);
    post.setHeader(“Connection”, “Keep-Alive”);


    StringBody latitudeCB=new StringBody(latitude);
    StringBody longitudeCB=new StringBody(longitude);
    StringBody captionCB=new StringBody(caption);
    StringBody deviceCB=new StringBody(“android”);

    entitity.addPart(“file”, bab);
    //entitity.addPart(“file”, imageFileCB);
    entitity.addPart(“latitude”, latitudeCB);
    entitity.addPart(“longitude”,longitudeCB );
    entitity.addPart(“device”, deviceCB);
    entitity.addPart(“description”, captionCB);


    HttpResponse response=httpclient.execute(post,con);
    if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK)
    String result = EntityUtils.toString(response.getEntity());
    Log.i(“result is”, result);
    Toast.makeText(ctx, “doen”, Toast.LENGTH_LONG).show();
    }catch (Exception e) {
    // TODO: handle exception



  42. Hello sir,
    It is working fyn for me but will you please give me code sample of web service you made for this application in json. Actually I’m not that much familiar with writing the web services in JSOn if you give me the code for sample then it will help me in future to create Json service for my applications…

    Thanks in advance
    My Id:

  43. Hi vikas,
    I have tried to send image on a web service through ksoap libraries everything is going good but the problem is that when I click to upload the image on server it will give me a error of Soapfault: server error i.e

    SoapFault – faultcode: ‘soap:Server’ faultstring: ‘Server was unable to process request. —> Argument ‘Length’ must be greater or equal to zero.’ faultactor: ‘null’ detail: org.kxml2.kdom.Node@44c33850

    Can’t get it how to solve this if you have a clue then plz help me out thanks……..

  44. when i click on upload button i get message request time failed: Address family not supported by protocol please give me suggestion how to make this code working
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    public class UserLoging extends Activity implements OnClickListener {
    private static final String developerKey = “AI39si7BDlkqHaPOQoMkjpxifa-E4vT4liPmDTKiWLGBgrSzRqJjEVlcDLi_VMuxZTLWBe4_K9C8NHNuMNf0bWVUCWflcI-dRw”;
    private static final String clientId = “”;
    String logingResult = null;
    Button ok;
    String username;
    String password;
    EditText uname;
    EditText pword;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    ok = (Button) findViewById(;
    uname = (EditText) findViewById(;
    pword = (EditText) findViewById(;


    public void UploadVideo() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(“”);
    httppost.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
    StringEntity entity = new StringEntity(“Email=” + username
    + “&Passwd=” + password
    + “&service=youtube&source=QikShare1”, “UTF-8”);

    HttpResponse response = httpclient.execute(httppost);
    logingResult = EntityUtils.toString(response.getEntity());
    }catch (ClientProtocolException e) {
    // TODO: handle exception
    }catch (Exception e) {
    // TODO: handle exception
    YouTubeService service = new YouTubeService(clientId,developerKey);

    try {
    service.setUserCredentials(username, password);

    } catch (AuthenticationException auth) {
    VideoEntry newEntry = new VideoEntry();
    YouTubeMediaGroup mediaGroup = newEntry.getOrCreateMediaGroup();
    mediaGroup.setTitle(new MediaTitle());
    mediaGroup.getTitle().setPlainTextContent(“QikShare Videos”);
    mediaGroup.addCategory(new MediaCategory(
    YouTubeNamespace.CATEGORY_SCHEME, “funny”));
    mediaGroup.setKeywords(new MediaKeywords());
    mediaGroup.setDescription(new MediaDescription());
    “Custom description here”);
    mediaGroup.addCategory(new MediaCategory(
    YouTubeNamespace.DEVELOPER_TAG_SCHEME, “mydevtag”));
    mediaGroup.addCategory(new MediaCategory(
    YouTubeNamespace.DEVELOPER_TAG_SCHEME, “anotherdevtag”));
    newEntry.setGeoCoordinates(new GeoRssWhere(37.0, -122.0));
    newEntry.setLocation(“Mountain View, CA”);

    MediaFileSource ms = new MediaFileSource(new File(getIntent()
    .getExtras().getString(“shareVideo”)), “video/mp4”);
    //String uploadUrl = “”;
    String uploadUrl = “”;
    try {

    VideoEntry createdEntry = service.insert(new URL(uploadUrl),

    } catch (MalformedURLException e)

    } catch (IOException e) {
    } catch (ServiceException e) {


    public void onClick(View view) {
    if (view == ok) {
    public void onBackPressed() {

  45. ******SHOWS ERROR******

    -05-07 16:46:27.799: E/org.json.JSONException(13563): Value <?xml of type java.lang.String cannot be converted to JSONObject
    05-07 16:46:27.799: E/org.json.JSONException(13563): org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
    05-07 16:46:27.799: E/org.json.JSONException(13563): at org.json.JSON.typeMismatch(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at org.json.JSONObject.(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at org.json.JSONObject.(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at com.uploadfile.uploadfile$ImageUploadTask.onPostExecute(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at com.uploadfile.uploadfile$ImageUploadTask.onPostExecute(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.AsyncTask.finish(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.AsyncTask.access$300(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.AsyncTask$InternalHandler.handleMessage(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.Handler.dispatchMessage(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.Looper.loop(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at
    05-07 16:46:27.799: E/org.json.JSONException(13563): at java.lang.reflect.Method.invokeNative(Native Method)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at java.lang.reflect.Method.invoke(
    05-07 16:46:27.799: E/org.json.JSONException(13563): at$
    05-07 16:46:27.799: E/org.json.JSONException(13563): at
    05-07 16:46:27.799: E/org.json.JSONException(13563): at dalvik.system.NativeStart.main(Native Method)
    05-07 16:53:52.929: W/IInputConnectionWrapper(13563): showStatusIcon on inactive InputConnection
    05-07 17:30:44.089: I/ResolverActivity(13935): mcc=405
    05-07 17:30:44.089: D/palu(13935): Change Gmail title to Google Mail for any German SIM enabled device
    05-07 17:30:47.239: W/IInputConnectionWrapper(13935): showStatusIcon on inactive InputConnection
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): Text may not be null
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): java.lang.IllegalArgumentException: Text may not be null
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at org.apache.http.entity.mime.content.StringBody.(
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at org.apache.http.entity.mime.content.StringBody.(
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at com.uploadfile.uploadfile$ImageUploadTask.doInBackground(
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at com.uploadfile.uploadfile$ImageUploadTask.doInBackground(
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at android.os.AsyncTask$
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at java.util.concurrent.FutureTask$Sync.innerRun(
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at java.util.concurrent.ThreadPoolExecutor.runWorker(
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at java.util.concurrent.ThreadPoolExecutor$
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at

    On PHP side following code is written,

    I have integrated httpmime-4.1-beta1.jar in libs dir.


  46. Hi Vikas,thank you for your code,i am new with android programming.
    I’m interested to automatically take a photo and upload every x minutes ,is it possibile with some modification in your code?

    Thank you very much!

    1. Hi Vikas,
      first of all, really thank you for this code. really save my day. im newbie in android and im working on a project. this application almost done.. just that when i click upload button it shows “The application AndroidImageUpload (process com.isummation.imageupload) has stopped unexpectedly”. Your response would means so much.

  47. Hi i have tried your code and it’s fantastic one, but i need few changes in my application i want user will be able to capture an image and at the same time send that captured image to Remote Server directly using IP Address….i am very open to do changes in your existing code, please help me……..Thanks

  48. Hi,
    Your code is very nice and very useful to me.
    But since i would like to use asp in the server side.
    Any one can kindly provide the solution.

      1. I have get the freeaspupuload and tried.
        still failed to upload by classic asp.
        I would like to know did I need to change the source of your Android on sending the entity parameter to ASP? Just using the same android code is ok?

        Thanks in advance

  49. Hello,
    Actually i am completely new to this Android App Development..I have an assignment to upload an image from User’s mobile to Server along with its tag..i tried your project but it gives me error(red marks across the folder in eclipse)..cudnt even remove it.Also i included the external thhp client jar file in it..Could u plz help

  50. Nice tutorial for a new learner like me !!! greatly appreciated !
    but then I have a few question, where will all these photo upload to ?
    I’ve tested with my mobile phone, once the photo is chosen and the upload button clicked, the program will go forced close. 😦

  51. When I have tested it on Galaxy Tab it does nt work for me can u pls guide me is it version compatibility problem or anything else

  52. hii.. am getting the following error while executing the source code.. pls tel me the solution..
    Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.mime.MultipartEntity
    10-16 17:50:58.501: E/AndroidRuntime(14817): at com.isummation.imageupload.ImageUpload$ImageUploadTask.doInBackground(
    10-16 17:50:58.501: E/AndroidRuntime(14817): at com.isummation.imageupload.ImageUpload$ImageUploadTask.doInBackground(

    10-16 17:50:59.901: E/WindowManager(14817): at com.isummation.imageupload.ImageUpload$1.onClick(

  53. Thank you so much for this!! But I have a question about saving the photo onto the server. If I send a filebody or bytearraybody to the server, what is the php syntax to get the result?

    I used to follow the Base64 method ( where I convert the bitmap into a bytearray, and then change then bytearray into a string via Base64 — and then pass this string to php — and finally decode the Base64 string to get the bytearray back. But this method takes too much memory and this old method is really pointless now that I learned I can pass the filebody or byearraybody directly.

    So if you can please point me to the right direction to how to extract the image content in php — much appreciated!

  54. Hello 🙂 Vikas!
    I just start to study android these days and your posts are really helpful to me.
    I want to say thank you first.
    During coding, I have some questions to ask. I hope you can see this and reply.
    I added external jar as you said but there are some errors which i cannot know.
    On’s first line
    package com.isummation.imageupload;
    77th line
    inflater.inflate(, menu);
    85th line
    96th line
    153rd line
    getString(R.string.WebServiceURL)-> I think I can write URL
    252nd line
    if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)

    Please help me to find out the way TT

  55. sir,am a newcomer in this field,i have used your code but i am getting errors on Multipartentity,stringbody and ByteArrayBody,can u please explain the reasons for this..

    thank u

  56. Hey there! This post could not be written any better!
    Reading through this post reminds me of my old room mate!
    He always kept chatting about this. I will forward
    this post to him. Fairly certain he will have a good read.
    Thank you for sharing!

  57. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored material
    stylish. nonetheless, you command get bought an edginess over that
    you wish be delivering the following. unwell unquestionably
    come further formerly again since exactly the same nearly
    very often inside case you shield this hike.

  58. I’ve appreciate approximately nutrients here. Positively anyway value bookmarking regarding revisiting. I surprise emphatically how a large amount exertion a person put to help compose this classify of magnificent enlightening website.

  59. i am able to select image from gallery download but when i select that image nothing happens just stay on the screen …so plas help me to solve this..and what is cold fusion file….and how to use it can u tell me???

  60. hi!
    I have a problem concerning this part

    in imagupload_menu.xml

    There is this error: – Element type “item” must be followed by either attribute specifications, “>”
    or “/>”.
    – [I18N] Hardcoded string “Gallery”, should use @string resource

    What can I do? please help!

  61. there is no way to upload image while testing in mobile. I has only upload button but no browse button to set an image.
    can any one help me the way to browse an image.


  62. Thank you for adding this blog.

    let me ask you. Using Apache library , i fear if it increases the size of the application?
    Can you let me know if any implications on the size of the app because of using an apache library which is intended for web browsers?

  63. hi vikas.. I am having trouble importing the http mime. I have included the required jar files in lib still unable to import it. Please help

  64. can u post server side code(in java) with REST web-service for file uploading activity from android..plz…do post as early as possible…It is part of our BE project…
    It would be a grt help for us….

  65. Hello thanx for code! It’s was very helpfull as i am a new in android programming. Although I had a problem with: import org.apache.http.entity.mime.content.ByteArrayBody; The “ByteArrayBody” is red, what can i do?

  66. Hi Vikas; I have been using your code to pick image from gallery since 2011 (started with Android 2.1). It has worked great up until KitKat. I’ve tried for hours amending the code to work with 4.4.2 (API 19), but still don’t get it. Help Please.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s