Upload images to server from Android app

This is a simple example to upload images to hosted server from android app with help of PHP script.

First of all we need to created the PHP script which is hosted in server.

uploadImage.php


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php
//path starts from the default root directory
$target_path = "images/";

$base=$_REQUEST['image'];
$name=$_REQUEST['name'];
echo $base;
echo $name;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');

$file = fopen($target_path, 'wb');
$file = fopen($name, 'wb');
fwrite($file, $binary);
fclose($file);

copy($name,$target_path.$name);
?>

Then create an Android Application Project using eclipse or any other IDE.











After creating new android project open the activity_main.xml.



update the activity_main.xml with following code.




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btnSelectImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="78dp"
        android:layout_marginTop="58dp"
        android:text="Select Image" />

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/btnSelectImg"
        android:layout_marginBottom="82dp"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>


Then edit the MainActivity.java. Before that we need to need the Base64.java file since we upload images from mobile devices images should be smaller in size. So to do that we can encode the image using bitmap methods of Base64.java.
Download Base64.java file

Now we can edit MainActivity.java

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package com.example.imageupload;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
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.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

     private static final int PICK_FROM_FILE = 1;
     private Uri mImageCaptureUri;
     private AlertDialog dialog;
  // new part 1
  public static SharedPreferences pref;
  public static Editor editor;
  public static String pp="";
  String  foo = null;

  Button btnimage;
  ImageView img1;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   //captureImageInitialization();
   
   btnimage = (Button) findViewById(R.id.btnSelectImg);
   img1 = (ImageView) findViewById(R.id.img);
   btnimage.setOnClickListener(new OnClickListener() {
    
    @Override
    public void onClick(View arg0) {
     captureImageInitialization();
     dialog.show(); 
    }
   });
   
  // 
  }
  
  @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if (resultCode != RESULT_OK)
                 return;

          switch (requestCode) {
          
          case PICK_FROM_FILE:
                  // After selecting image from files, save the selected path
                 mImageCaptureUri = data.getData();
                 Log.d("uri", mImageCaptureUri.toString());
                 try{
                 Bitmap bm = BitmapFactory.decodeStream(
                      getContentResolver().openInputStream(mImageCaptureUri));
                 new uploadProImgAsync().execute(bm);
                 Toast.makeText(getApplicationContext(), "entered to async task", Toast.LENGTH_SHORT).show();
                 img1.setImageBitmap(bm);
                 }catch(Exception e){
                  Log.e("error",e.toString());
                 }
                 break;      
          }        
   }
  
  private void captureImageInitialization() {
        final String[] items = new String[] {
                "Select from gallery","Cancel"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                     android.R.layout.select_dialog_item, items);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Select Wallpaper");
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int item) {                 
                      if(item==0){
                            /*
                              To select an image from existing files, 
                              use Intent.createChooser to open image chooser. Android will
                              automatically display a list of supported applications,
                              such as image gallery or file manager. */
                            Intent intent = new Intent();

                            intent.setType("image/*");
                             intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(Intent.createChooser(intent,
                                          "Complete action using"), PICK_FROM_FILE);    
                     }else{
                      dialog.dismiss();
                     }
               }
        });
        dialog = builder.create();
  }
  //upload profile image to server
  private class uploadProImgAsync extends AsyncTask<Bitmap, Integer, String>{
   private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);     
   @Override  
         protected void onPreExecute()  
         {  
          Dialog.setMessage("Loading data...");
             Dialog.show();
         }
   
   @Override
   protected String doInBackground(Bitmap... bit) {
    Bitmap bitmap = bit[0];
    InputStream is;
    BitmapFactory.Options bfo;
    ByteArrayOutputStream bao ;
     
    bfo = new BitmapFactory.Options();
    bfo.inSampleSize = 2;
    
    bao = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte [] ba = bao.toByteArray();
    String ba1 = Base64.encodeBytes(ba);
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("image",ba1));
    nameValuePairs.add(new BasicNameValuePair("name","my_"+String.valueOf(System.currentTimeMillis())+".jpg"));
    Log.v("log_tag", System.currentTimeMillis()+".jpg");
    
    try{
     HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new 
           HttpPost("http://your_domain_name/uploadProImage.php");
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
           HttpResponse response = httpclient.execute(httppost);
           HttpEntity entity = response.getEntity();
           is = entity.getContent();
           Log.v("log_tag", "In the try Loop" );
    }catch(Exception e){
     Log.v("log_tag", "Error in http connection "+e.toString());
    }  
    return "Success";
   }
   
   protected void onPostExecute(String result) {
    Dialog.dismiss();
   } 
  }
}

Then edit the AndroidManifest.xml
add the following statement before <Application> tag

1
<uses-permission android:name="android.permission.INTERNET" />

Now we are done with editing.
Important: Make sure that you have enable WiFi or mobile internet connection before launch the app. Because Asynchronous task is sending data to server as a background process using HTTP post method.
Or less you can check internet availability before proceed the process.

1 comment: