Android: Image upload activity


Hi,

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

imageupload.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/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" />
</RelativeLayout>

ImageUpload.java:

package com.isummation.imageupload;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
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. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.imageupload);

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

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

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.imageupload_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.ic_menu_gallery:
			try {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						PICK_IMAGE);
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.exception_message),
						Toast.LENGTH_LONG).show();
				Log.e(e.getClass().getName(), e.getMessage(), e);
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	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();

					// MEDIA GALLERY
					String selectedImagePath = getPath(selectedImageUri);

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

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

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

				MultipartEntity entity = new MultipartEntity(
						HttpMultipartMode.BROWSER_COMPATIBLE);

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

				String sResponse = reader.readLine();
				return sResponse;
			} catch (Exception e) {
				if (dialog.isShowing())
					dialog.dismiss();
				Toast.makeText(getApplicationContext(),
						getString(R.string.exception_message),
						Toast.LENGTH_LONG).show();
				Log.e(e.getClass().getName(), e.getMessage(), e);
				return null;
			}

			// (null);
		}

		@Override
		protected void onProgressUpdate(Void... unsued) {

		}

		@Override
		protected void onPostExecute(String sResponse) {
			try {
				if (dialog.isShowing())
					dialog.dismiss();

				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,
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(getApplicationContext(),
								"Photo uploaded successfully",
								Toast.LENGTH_SHORT).show();
						caption.setText("");
					}
				}
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.exception_message),
						Toast.LENGTH_LONG).show();
				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) {
			// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
			// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			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)
				break;
			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);

		imgView.setImageBitmap(bitmap);

	}
}

imageupload_menu.xml:

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

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.

Added:

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"
 			filefield="uploaded"
 			destination="#Variables.FolderPath#"
 			nameconflict="makeunique"
 			/>

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

Update:

Download source code: Download

Advertisements

200 thoughts on “Android: Image upload activity

  1. Pingback: Android: Upload image or file using http POST multi-part « Vikas Patel's Blog

  2. sathish

    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 :– http://domaim.com/upload_video.php) 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
    sathish

    Reply
    1. Vikas Post author

      As explained, FileBody() can upload any file. Browse for the recorded video, same as above, then upload it with FileBody(). More about attachment is here.

      Reply
      1. Vikas Post author

        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. ammu

        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. Vikas Post author

        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.

  3. Muhammad Asif

    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.

    Reply
    1. Vikas Post author

      I think you can copy and paste the code into notepad or into your editor. Problem with attaching a zip is the WordPress hosting limitation.

      Reply
      1. gangeshwari

        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. Vikram Kedilaya

      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.

      Reply
  4. Are

    I have problems:

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

    Reply
      1. sathyak2015

        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

  5. shivam sabhlok

    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

    Reply
  6. onDoi

    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.java /phocha/src/are/phocha line 149 Java Problem
    The method onPostExecute(String) of type phocha.phochaTask must override a superclass method phocha.java /phocha/src/are/phocha line 197 Java Problem
    The method onProgressUpdate(Void…) of type phocha.phochaTask must override a superclass method phocha.java /phocha/src/are/phocha line 192 Java Problem”

    Reply
  7. Vikas Post author

    @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()

    Reply
  8. onDoi

    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.

    Reply
    1. Vikas Post author

      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.

      Reply
  9. monster

    “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?

    Reply
  10. Austin

    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

    Reply
  11. Austin

    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

    Reply
  12. Austin

    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?

    Reply
      1. hesh

        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))
        System.IO.Directory.CreateDirectory(sDirectory);

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

        context.Response.Write(“1”);
        }
        else {
        context.Response.Write(“0”);
        }
        }
        public bool IsReusable {
        get {
        return false;
        }
        }
        }

  13. Austin

    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?

    Reply
  14. Austin

    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?

    Reply
    1. Vikas Post author

      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.

      Reply
      1. Austin

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

  15. Eka

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

    Reply
  16. dolly

    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?

    Reply
      1. Vikas Post author

        Yes, if you are using eclipse, then DMDS perspective allow us to push and pull files for Android emulator.

      2. yeowthiong

        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?

  17. Andy

    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.

    Regards

    Reply
  18. Saurabh

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

    how to solve this error?

    Reply
  19. Saurabh

    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”

    Reply
  20. Suresha

    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.

    Reply
  21. Ouii

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

    package file.up.load;

    import android.app.Activity;
    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.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Date;
    import android.os.Bundle;

    public class fileup extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

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

    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    File f = new File(“/sdcard/test.txt”);
    try {
    f.createNewFile();
    Date d = new Date();
    PrintWriter writer = new PrintWriter(f);
    writer.println(d.toString());
    writer.close();
    HttpClient client = new DefaultHttpClient();
    httpPostFileUpload(client, “/sdcard/test.txt”, “http://localhost/upload.php”, “uploadedfile”);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    });
    }
    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 {
    client.execute(request);
    } 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

    Reply
      1. Ouii

        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. Vikas Post author

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

  22. monu kumar

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

    Reply
      1. monu kumar

        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. Vikas Post author

      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.

      Reply
  23. monu kumar

    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………..

    Reply
  24. Paul

    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!!

    Reply
    1. Vikas Post author

      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.

      Reply
      1. Paul

        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: http://www.motobit.com/dlldownload/pASPUpl2.zip. 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!

  25. Ozman Khaled

    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

    Reply
  26. Raúl

    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.

    Raul

    Reply
  27. Raúl

    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:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.imageupload);
    imgView = (ImageView) findViewById(R.id.ImageView);
    upload = (Button) findViewById(R.id.Upload);
    caption = (EditText) findViewById(R.id.Caption);

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

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

    Reply
    1. Vikas Post author

      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.

      Reply
  28. Binesh J M

    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?

    Thanks
    Binesh J M

    Reply
    1. Vikas Post author

      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..

      Reply
  29. Mafe

    hi! does this upload image project can search the same images on web ?? or it only upload images ? thanks ..

    Reply
  30. Paul

    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??

    Reply
      1. Paul

        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! 🙂

        Thanks

  31. ece çalıkuş

    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.

    Reply
      1. bhavna

        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

  32. james

    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”);
    json_encode($response);
    ?>

    Any ideas?
    Thanks
    James

    Reply
    1. Vikas Post author

      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.

      Reply
  33. odread

    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: com.android.internal.view.IInputMethodClient$Stub$Proxy@4387abf0
    09-26 07:55:38.685: ERROR/AndroidRuntime(444): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception

    Thanks

    Reply
  34. sudarshan

    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..

    Reply
    1. David

      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)

      Reply
      1. sudarshan

        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. Vikas Post author

        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.

  35. Akshay Somvanshi

    How to setup the server….can u pls tell me because i want to show the server for my project demo also…..

    Reply
  36. Pradeep VR

    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));
    }
    }
    httpPost.setEntity(reqEntity);

    Thnx in advance………

    Reply
  37. Matt

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

    This doesn’t work right in honeycomb initially:
    http://stackoverflow.com/questions/6277584/android-honeycomb-networkonmainthreadexception-even-when-using-asynctask-and-no

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

    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.

    Reply
  38. Shaahin

    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

    Reply
  39. Girish

    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..

    Reply
      1. titus

        hi i need to copy a file from one dirctory of folder to another folder can u give a source code for this

  40. Lenin Yee

    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.

    Thanks!

    Reply
  41. Soroush

    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?

    Reply
    1. Vikas Post author

      Yes, you will need a webserver with some language like php, .net or any other platform. Then you’ll be able to receive image in form field.

      Reply
      1. harsh

        hey vikas could u know or have any site or any reference code for server side in Php Pl help me

  42. Siddhesh

    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

    Reply
  43. rexx

    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

    Reply
  44. Kartik Shah (@_ikartikshah)

    this however gives me a failure response on server side
    @Override
    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();
    //MediaStore.Images.Media.DATA

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

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

    ImageView show=(ImageView)findViewById(R.id.share_rcb_image);
    show.setImageURI(imageUri);
    TextView describe=(TextView)findViewById(R.id.describe);
    final EditText caption_des=(EditText)findViewById(R.id.cap_des);
    Button upload=(Button)findViewById(R.id.upload_image);
    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=”http://www.royalchallengers.com/mobile-app/services/rcb_moment_add.php”;

    HttpPost post=new HttpPost(url);

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

    try{
    if(latitude==null)
    {
    longitude=”0″;
    latitude=”0″;
    }

    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);

    post.setEntity(entitity);

    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
    e.printStackTrace();
    }
    }
    });

    upload.setVisibility(View.VISIBLE);
    caption_des.setVisibility(View.VISIBLE);
    describe.setVisibility(View.VISIBLE);
    show.setVisibility(View.VISIBLE);

    }
    }

    Reply
  45. Amit

    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: kaushik101in@gmail.com

    Reply
  46. Amit

    Hi vikas,
    I have tried to send image on a vb.net 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……..

    Reply
  47. ikrar

    when i click on upload button i get message request time failed: java.net.SocketException: Address family not supported by protocol please give me suggestion how to make this code working
    package np.global.QikShare;
    import com.google.gdata.client.youtube.*;
    import com.google.gdata.data.geo.impl.*;
    import com.google.gdata.data.media.*;
    import com.google.gdata.data.media.mediarss.*;
    import com.google.gdata.data.youtube.*;
    import com.google.gdata.util.*;
    import java.io.IOException;
    import java.io.File;
    import java.net.URL;
    import java.net.MalformedURLException;
    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.app.Activity;
    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 = “205782079657-gkkqrrrcd0h6fv9mvjgob8se05c7o01c.apps.googleusercontent.com”;
    String logingResult = null;
    Button ok;
    String username;
    String password;
    EditText uname;
    EditText pword;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.userlogin);
    ok = (Button) findViewById(R.id.btn_login);
    ok.setOnClickListener(this);
    uname = (EditText) findViewById(R.id.txt_username);
    pword = (EditText) findViewById(R.id.txt_password);

    }

    public void UploadVideo() {
    username=uname.getText().toString();
    password=pword.getText().toString();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(“https://www.google.com/accounts/ClientLogin”);
    httppost.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
    try
    {
    StringEntity entity = new StringEntity(“Email=” + username
    + “&Passwd=” + password
    + “&service=youtube&source=QikShare1”, “UTF-8”);

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

    try {
    service.setUserCredentials(username, password);

    } catch (AuthenticationException auth) {
    //auth.printStackTrace();
    }
    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.getKeywords().addKeyword(“myImportantKeyword”);
    mediaGroup.setDescription(new MediaDescription());
    mediaGroup.getDescription().setPlainTextContent(
    “Custom description here”);
    mediaGroup.setPrivate(false);
    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”);
    newEntry.setMediaSource(ms);
    //String uploadUrl = “http://uploads.gdata.youtube.com/feeds/api/users/default/uploads?access_token=logingResult”;
    String uploadUrl = “http://uploads.gdata.youtube.com/feeds/api/users/default/uploads”;
    try {

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

    } catch (MalformedURLException e)

    {
    //e.printStackTrace();
    } catch (IOException e) {
    //e.printStackTrace();
    } catch (ServiceException e) {
    //e.printStackTrace();
    }

    }

    @Override
    public void onClick(View view) {
    if (view == ok) {
    UploadVideo();
    }
    }
    public void onBackPressed() {
    System.exit(0);
    }
    }

    Reply
  48. Pingback: [TuFun] Android post image to server | Sean Wu Apps News Blog

  49. RoN

    ******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(JSON.java:107)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at org.json.JSONObject.(JSONObject.java:158)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at org.json.JSONObject.(JSONObject.java:171)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at com.uploadfile.uploadfile$ImageUploadTask.onPostExecute(uploadfile.java:204)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at com.uploadfile.uploadfile$ImageUploadTask.onPostExecute(uploadfile.java:1)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.AsyncTask.finish(AsyncTask.java:417)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.AsyncTask.access$300(AsyncTask.java:127)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.Handler.dispatchMessage(Handler.java:99)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.os.Looper.loop(Looper.java:130)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at android.app.ActivityThread.main(ActivityThread.java:3687)
    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(Method.java:507)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    05-07 16:46:27.799: E/org.json.JSONException(13563): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
    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.(StringBody.java:85)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at org.apache.http.entity.mime.content.StringBody.(StringBody.java:99)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at com.uploadfile.uploadfile$ImageUploadTask.doInBackground(uploadfile.java:164)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at com.uploadfile.uploadfile$ImageUploadTask.doInBackground(uploadfile.java:1)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at android.os.AsyncTask$2.call(AsyncTask.java:185)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
    05-07 17:31:11.199: E/java.lang.IllegalArgumentException(13935): at java.lang.Thread.run(Thread.java:1019)

    On PHP side following code is written,

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

    CAN YOU PLEASE HELP ME…ITS URGENT…THANKS IN ADVANCE

    Reply
  50. Roberto

    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!

    Reply
    1. Christina

      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.
      Regards,
      Christina

      Reply
  51. Pingback: Android Upload Image « tediscript.wordpress.com

  52. aMIT sURI

    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

    Reply
  53. Eddie

    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.

    Reply
      1. Vikas Post author

        Hey, please try to use freeaspupload . I am using it and it surely catch the file. Don’t have time to post

      2. Eddie

        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

  54. Jigar

    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

    Reply
  55. Kai

    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. 😦

    Reply
  56. Meghana

    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

    Reply
  57. Navya

    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(ImageUpload.java:152)
    10-16 17:50:58.501: E/AndroidRuntime(14817): at com.isummation.imageupload.ImageUpload$ImageUploadTask.doInBackground(ImageUpload.java:1)

    at android.app.ProgressDialog.show(ProgressDialog.java:99)
    10-16 17:50:59.901: E/WindowManager(14817): at com.isummation.imageupload.ImageUpload$1.onClick(ImageUpload.java:63)

    Reply
  58. Patrick

    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 (http://blog.sptechnolab.com/wp-content/uploads/2011/03/phpad1.png) 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!

    Reply
  59. hooooooong

    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 ImageUpload.java’s first line
    package com.isummation.imageupload;
    77th line
    inflater.inflate(R.menu.imageupload_menu, menu);
    85th line
    case R.id.ic_menu_gallery:
    96th line
    getString(R.string.exception_message)
    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

    Reply
  60. Pingback: Android file upload: Access file data from MultipartEntity ByteArrayBody not $_FILES using PHP? | BlogoSfera

  61. Ajisha

    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

    Reply
  62. dev

    Hey Vikas….

    Will you please guide me how to do in server part with coldfusion. Please help me out.Thank you

    Reply
  63. smallidea2077.jigsy.com

    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!

    Reply
  64. Cassandra

    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.

    Reply
  65. karpacz silvester

    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.

    Reply
  66. Jay

    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???

    Reply
  67. Anna

    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!

    Reply
  68. Saran

    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.

    Thanks

    Reply
  69. Sunil C

    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?

    Reply
  70. richa

    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

    Reply
  71. Vishal Kudale

    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….

    Reply
  72. Pingback: Fix Wordpress Upload Image Html Error Windows XP, Vista, 7, 8 [Solved]

  73. Pingback: Fix Http Error While Uploading Image In Wordpress Windows XP, Vista, 7, 8 [Solved]

  74. Pingback: Fix Android Picasa Upload Error Windows XP, Vista, 7, 8 [Solved]

  75. Pingback: Fix Image Upload Error In Magento Windows XP, Vista, 7, 8 [Solved]

  76. Xaroulita LaLoca

    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?

    Reply
  77. Paul Fountain

    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.

    Reply

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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