Hi ANDROIDians in today’s tutorial I will show you how to send an image to server using POST method in ANDROID.
Uploading an image to server is a basic requirement in many of our application.
Sending data to server which is using a PHP Script is already explained in this example .
Now in this example I will show you how to send an image file.
For that first we have to read the file, put it in nameValuePairs and then send using HttpPost.
I have already shown you three other methods on uploading a file to server. If you want you can check these posts.
1. How to Upload Multiple files in one request along with other string parameters in android?
2. Uploading audio, video or image files from Android to server.
3. How to upload an image from Android device to server? – Method 4
These are for downloading files from the server.
1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?
Now can we quickly go to the code.
This is the main java file source code UploadImage.java
package pack.coderzheaven;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;
public class UploadImage extends Activity {
InputStream inputStream;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon); ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "+e.toString());
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
Now download a file from here which encodeBytes in Base64 Format. Put this file in the same package of UploadImage.java. See the screenshot.
Now the server part.
Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this code into it.
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>
Now run your program and check the folder in which your php file resides.
Note: Make sure your server is running.
Here I am uploading the icon image itself.
If you want to upload another file in your SDCARD you have to change this line to give the exact path
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
For example if I have to upload a file residing in my SDCARD I would change the path like this.
Bitmap bitmap = BitmapFactory.decodeFile(“/sdcard/android.jpg”);
This tutorial explains how to create an SDCARD and start the emulator with the SDCARD
and this tutorial explains how to put file inside your emulator SDCARD
if you want to use the android using php and mysql
please check these posts.
1. Android phpMysql connection
2. Android phpmySQL connection redone.
Please comment if you didn’t get it right or you like this post.



























Just what I was looking for, appreciate it for posting .
Hi, Please could you tell me what i need to use for main.xml file, thankyou
Lucy
Hello Lucy..
The main.xml file is for the interface. Since in this example it shows how to upload an image to server there is actually no need of an interface. You can put anything in the main.xml file. For example you can have a button which when clicked will upload the image, then put the code provided inside the button click, that’s all.
You have to provide a layout for the setContentView() otherwise the program will not run.
Hi James,
Thanks for the quick response, I confess, i’m an android newbie
Would you be ever so kind as to help me out getting this to work, i guess all i need is the main.xml with a button that will upload the image, and the code to know that the button is there.
Hope you can help, you can email me if you wish
Thankyou
Lucy
@Lucy : Please wait for the answer we will contact you shortly.
Very nice tutorial:)
Thank u .Nice Tuto:)
I would like to uploade many images..
How can I give a name for each image?
Thanks.
It helps me so much
I prefer to send it just as a byte array
I don’t code for the server.
Thanks a lot
but i have problem with Base64.encodeBytes(byte_arr);
it gives me error :S
Did you include the file Base64.java.
Hi, I have the same problem with Peter gabra, and I have include the Base64.java in the src, could you help me to fixed it?
Did you download the complete source code. Try changing the filename to something else and change accordingly in the main file.
Hi, thanks my problem solve now. I want to ask about base 64, because it just possible to send the image with small size, is there possible to send the image in big size to server using base64?
thanks
hei james nice tutorial. I am a newbie for android. May i have the full source code for this? and also i cannot find the “get picture from sd card gallery” thing like a picker in your code. so how do i pick the pic from my gallery?
Hi,,
Nice post … But I have question what about image captured by Image and store it at Media.EXTERNAL_CONTENT_URI location.
Thanks
It works fine, thanks.
On the server the image gets “uploaded_image” filename.
I’m sending to the server a file from my device’s sd card, it works ok (I have to downsize it though because I get out of memory error)
I want the file name to be the same as the original, how can I do that??
Hey LamprosGk : If you want the filename as such then try this example
http://coderzheaven.com/2011/08/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/
or try this
http://coderzheaven.com/2011/08/uploading-audio-video-or-image-files-from-android-to-server/
Thanks James
I’ve found out how to do it..
(passed the file name in nameValuePairs to the php file
Thank you very very very much!!! This has been a tremendous help!
I’d just like to add one small comment. I would suggest resizing the image before sending it the server because otherwise if the image is too big, it is very likely that you’ll get an out of memory exception.
Bitmap resizedDishImage = Bitmap.createScaledBitmap(dishImage, 150, 150, false);
Hello,
I tried your code and it works fine with a local server, but with a remote server it doesn’t work
Have you an idea why ?
No, it works perfectly with any server. Please check your server address or anyother parameters you are sending.
Hello,
Very nice post. Is there a way I can do this using a web app instead of an installed app?
thank you!
I cant see the php code.
Sorry Hari that was problem with my syntax highlighter, please check the post again.
Hello James,
Thanks for the reply. Its working very fine. Thanks man
Hi,
the encodeBytes method is giving me an error saying “encodedBytes is undefined for type Base64″ . i have downloaded the Base64 class, and inserted it into my project..could you please help me????
hey this “Bitmap bitmap = BitmapFactory.decodeFile(“/sdcard/mypic.jpg”);” does not work, do you have any idea why?
but if it works whrn i used Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
This is because you don’t have mypic.jpg in that path.
hi i run ur apps successfully…result also displayed successfully.Image upload complete!!, Please check your php file directory……But my doubt is where is uploaded file is saved..how is know the above image is successfully uploaded…where i see the image after successful completion…
The uploaded file will be saved in the uploads directory in your server where your php file is located.
Wooow… thanku so much. It works great. And how can I upload an image which is captured? where I have modify in this code…?
hi!
can anyone suggest me an alternative to above server side phpscript.
Any help will be appreciated..
hi,
its so excellent tutorial…..i m getting a problem……i want to upload an image on jboss server……what i has to bb done on jboss server……what code i hv to write there…….plz any one guide me………..