Android Select Image from Gallery Upload to Server example tutorial using JSON

How to send image along with Text using JSON PHP and store image path in MySQL database.

In this tutorial we are going to upload image on server using AsyncTask and doInBackground task. Sending image to server is very much typical for all the android developers so in this tutorial we are going to create an android application which will upload the selected image online directly to server. We will using PHP script to get and sending image and storing that image to folder and store the image name with its complete path into MySQL database. So here is the complete step by step tutorial for Android Select Image from Gallery Upload to Server example tutorial.

What we are doing in this project :

We are creating a folder named as “images” on our online web hosting server and after that we will create a MySQL database and inside that database we will create a table named as “ImageUpload”. There are three Fields inside that table id, image_data and image_tag . After that we will create android code which will send the selected image to server.

android-project-download-code-button

Android Select Image from Gallery Upload to Server example tutorial.

Please add INTERNET permissions and WRITE_EXTERNAL_STORAGE permission to your AndroidManifest.xml file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Code for MainActivity.java file.

package com.android_examples.imageuploadonserver_android_examplescom;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.io.BufferedReader;
import java.net.URLEncoder;
import java.util.Map;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;

public class MainActivity extends Activity {

    Button GetImageFromGalleryButton, UploadImageOnServerButton;

    ImageView ShowSelectedImage;

    EditText GetImageName;

    Bitmap FixBitmap;

    String ImageTag = "image_tag" ;

    String ImageName = "image_data" ;

    String ServerUploadPath ="http://androidblog.esy.es/upload-image-server.php" ;

    ProgressDialog progressDialog ;

    ByteArrayOutputStream byteArrayOutputStream ;

    byte[] byteArray ;

    String ConvertImage ;

    String GetImageNameFromEditText;

    HttpURLConnection httpURLConnection ;

    URL url;

    OutputStream outputStream;

    BufferedWriter bufferedWriter ;

    int RC ;

    BufferedReader bufferedReader ;

    StringBuilder stringBuilder;

    boolean check = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GetImageFromGalleryButton = (Button)findViewById(R.id.button);

        UploadImageOnServerButton = (Button)findViewById(R.id.button2);

        ShowSelectedImage = (ImageView)findViewById(R.id.imageView);

        GetImageName = (EditText)findViewById(R.id.editText);

        byteArrayOutputStream = new ByteArrayOutputStream();

        GetImageFromGalleryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();

                intent.setType("image/*");

                intent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);

            }
        });


        UploadImageOnServerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                GetImageNameFromEditText = GetImageName.getText().toString();

                UploadImageToServer();

            }
        });
    }

    @Override
    protected void onActivityResult(int RC, int RQC, Intent I) {

        super.onActivityResult(RC, RQC, I);

        if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {

            Uri uri = I.getData();

            try {

                FixBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

                ShowSelectedImage.setImageBitmap(FixBitmap);

            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

    public void UploadImageToServer(){

        FixBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);

        byteArray = byteArrayOutputStream.toByteArray();

        ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

        class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {

            @Override
            protected void onPreExecute() {

                super.onPreExecute();

                progressDialog = ProgressDialog.show(MainActivity.this,"Image is Uploading","Please Wait",false,false);
            }

            @Override
            protected void onPostExecute(String string1) {

                super.onPostExecute(string1);

                progressDialog.dismiss();

                Toast.makeText(MainActivity.this,string1,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Void... params) {

                ImageProcessClass imageProcessClass = new ImageProcessClass();

                HashMap<String,String> HashMapParams = new HashMap<String,String>();

                HashMapParams.put(ImageTag, GetImageNameFromEditText);

                HashMapParams.put(ImageName, ConvertImage);

                String FinalData = imageProcessClass.ImageHttpRequest(ServerUploadPath, HashMapParams);

                return FinalData;
            }
        }
        AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
        AsyncTaskUploadClassOBJ.execute();
    }

    public class ImageProcessClass{

        public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {

            StringBuilder stringBuilder = new StringBuilder();

            try {
                url = new URL(requestURL);

                httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setReadTimeout(20000);

                httpURLConnection.setConnectTimeout(20000);

                httpURLConnection.setRequestMethod("POST");

                httpURLConnection.setDoInput(true);

                httpURLConnection.setDoOutput(true);

                outputStream = httpURLConnection.getOutputStream();

                bufferedWriter = new BufferedWriter(

                        new OutputStreamWriter(outputStream, "UTF-8"));

                bufferedWriter.write(bufferedWriterDataFN(PData));

                bufferedWriter.flush();

                bufferedWriter.close();

                outputStream.close();

                RC = httpURLConnection.getResponseCode();

                if (RC == HttpsURLConnection.HTTP_OK) {

                    bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                    stringBuilder = new StringBuilder();

                    String RC2;

                    while ((RC2 = bufferedReader.readLine()) != null){

                        stringBuilder.append(RC2);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return stringBuilder.toString();
        }

        private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {

            stringBuilder = new StringBuilder();

            for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {
                if (check)
                    check = false;
                else
                    stringBuilder.append("&");

                stringBuilder.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));

                stringBuilder.append("=");

                stringBuilder.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
            }

            return stringBuilder.toString();
        }

    }
}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<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:background="#FFF9C4"
    tools:context="com.android_examples.imageuploadonserver_android_examplescom.MainActivity">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="CLICK HERE TO SELECT IMAGE FROM GALLERY"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="CLICK HERE TO UPLOAD SELECTED IMAGE ON SERVER "
        android:id="@+id/button2"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_above="@+id/button2"
        android:layout_centerHorizontal="true"
        android:hint="Enter Image Name Here"
        android:gravity="center"
        />

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="270dp"
        android:id="@+id/imageView"
        android:layout_below="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/editText" />

</RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android_examples.imageuploadonserver_android_examplescom">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Code for PHP files:

Code for upload-image-server.php file.

 <?php

include 'dbconfig.php';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
 
 if($_SERVER['REQUEST_METHOD'] == 'POST')
 {
 $DefaultId = 0;
 
 $ImageData = $_POST['image_data'];
 
 $ImageName = $_POST['image_tag'];

 $GetOldIdSQL ="SELECT id FROM ImageUpload ORDER BY id ASC";
 
 $Query = mysqli_query($conn,$GetOldIdSQL);
 
 while($row = mysqli_fetch_array($Query)){
 
 $DefaultId = $row['id'];
 }
 
 $ImagePath = "images/$DefaultId.png";
 
 $ServerURL = "http://androidblog.esy.es/$ImagePath";
 
 $InsertSQL = "insert into ImageUpload (image_data,image_tag) values ('$ServerURL','$ImageName')";
 
 if(mysqli_query($conn, $InsertSQL)){

 file_put_contents($ImagePath,base64_decode($ImageData));

 echo "Your Image Has Been Uploaded.";
 }
 
 mysqli_close($conn);
 }else{
 echo "Please Try Again";
 }

?>

Code for dbconfig.php file.

 <?php

//This script is designed by Android-Examples.com
//Define your host here.
$servername = "mysql.hostinger.in";
//Define your database username here.
$username = "u288012116_and";
//Define your database password here.
$password = "GArpOsx4KVa0GJDquJ";
//Define your database name here.
$dbname = "u288012116_and";

?>

Screenshots:

image_upload_1

image_upload_2

Android Select Image from Gallery Upload to Server example tutorial

image_upload_5

image_upload_4

Screenshot of MySQL database table :

image_upload_db_screenshot

Click here to download Android Select Image from Gallery Upload to Server example tutorial project with PHP files and MySQL database included.

84 Comments

  1. download link is not working

  2. How upload multi image selected to server?

  3. Dear Hamed, I have n’t try that now but regarding to your query i will soon upload a new tutorial.

  4. Thx for your nice TuT *.*

    I need pls Help, how can i upload all Photos without a Button ? im a photoman by paper and need to upload some images if we have a crash or stuff … then i want to start only the app and a message upload is succesfully but i want to upload all pictures i take… can this be possible ? if yes, pls show me how, thank you

    sorry for my crazy english

  5. Thx, sending a Email now!

  6. Hi sir,
    data is not inserting into database.please help me..
    Thanks

  7. thanks sir, tutorial very helpful, but why the image upload getting corrupt. The size just in bytes, can you help me please?

  8. Thank you sir,
    I have one question sir, How to upload any type of file(image,audio,text) into mysql database .is there any solution please..

  9. Hello sir ,
    I have to upload image using async task but at the same tyme i have to add header through async task.

  10. How can I update an image uploaded with specific id ? I’m looking forward to your response sir .

    • Caroline just use SQL update command on your server with php script and send the image id along with image to your server.

  11. Hello, this tutorial is veryhelpful to me.
    I want to ask how about upload image to server from captured image? not from gallery, can you help me sir? thank you

  12. Thank u so much for the great tutorial………..
    Sir i want to upload by clicking camera image please help me sir

  13. after running the app, when clicking the upload button, it uploads the image properly but whenever i try to upload another image it insert the mysql record properly but it upload the previously uploaded image and after restarting the app this process works fine for first time but it again upload previous image again.

  14. please help me sir.
    04-18 16:46:31.620 15081-15081/com.example.aimalkhan.test E/Zygote: MountEmulatedStorage()
    04-18 16:46:31.620 15081-15081/com.example.aimalkhan.test E/Zygote: v2
    04-18 16:46:31.650 15081-15081/com.example.aimalkhan.test E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
    04-18 16:46:51.530 15081-15081/com.example.aimalkhan.test E/ViewRootImpl: sendUserActionEvent() mView == null
    04-18 16:53:46.550 15081-15081/com.example.aimalkhan.test E/ViewRootImpl: sendUserActionEvent() mView == null

  15. Thanks so much . U are awesome chap. Cheers. I have one problem. Images taken by camera cannot upload. They simpliy display a blank toast after the connection timeout elapses some time of trying to send. How can i solve this. I fact this code is not uploading large images taken by camera. Please help. Thanks

    • Jose which internet connection is you using, because something because of slow net connectivity it will time out the upload season .

  16. hello, can you give me the my sql version for the php not my sqli version ? i really need it, thanks

  17. i use xampp can upload inage
    but
    if i use hostinger it can’t upload image
    database has data
    sor my english is bad

  18. can you put for us the code of how to retrieve the uploaded image and display them

  19. Sir
    Code is not working . when I run this code , it shows progress dialog but after that it does not show toast of your image has been uploaded and in database also record is not save
    plzz help sir

  20. Sir
    It shows blank toast after progress dialog

  21. Hello Sir ,
    Now code is working fine
    Sir can u give me some idea about how to upload multiple images in one activity at same time ???

  22. Hello again,
    Sir when I upload my first image to server and after that when I changed that image but it uploads first image every time
    why ???

  23. Warning: file_put_contents(images/35.png): failed to open stream: No such file or directory in
    /home/azizgh13/www/upload-image-server.php on line
    31

    Your Image Has Been Uploaded.

  24. Sir,
    How to upload picture that has large size ??

  25. But sir when I upload 2MB image I got this error in logcat

    Failed to allocate a 31826058 byte allocation with 4194304 free bytes and 20MB until OOM

  26. Sorry sir ,

    This is complete error when I try to upload 2MB image

    Caused by: java.lang.OutOfMemoryError: Failed to allocate a 29043478 byte allocation with 4194304 free bytes and 19MB until OOM

  27. Sir how can I upload mutiple texts and multiple images to the server?
    Plz help sir

Leave a Reply

Your email address will not be published. Required fields are marked *