ANDROID – Upload an image to a server

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.

Upload Image

Upload Image

However you can put in your own package but don’t forget to change the package name otherwise you will get error.

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.

I am saying the htdocs folder because I am using XAMPP. You change this according to your use.

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