Android image uploading to server from gallery

  • Replies:12
  • OpenNot stickiedAnswered
  • Forum posts: 17

Nov 12, 2014 7:55:39 AM via Website

Here is my code for Uploading image from gallery to server. when it upload the image name is stored in the mysql database also my question is how can i pass the title and description with this programme. Any help will be appreciated.

Java Code


import java.util.Calendar;
import java.util.GregorianCalendar;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener{

private TextView messageText;
private EditText title,desc;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;

private String upLoadServerUri = null;
private String imagepath=null;
public void onCreate(Bundle savedInstanceState) {


    uploadButton = (Button)findViewById(;
    btnselectpic = (Button)findViewById(;
    messageText  = (TextView)findViewById(;
    imageview = (ImageView)findViewById(;

    upLoadServerUri = "";
    ImageView img= new ImageView(this);



public void onClick(View arg0) {
Intent intent = new Intent();
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
else if (arg0==uploadButton) {

dialog =, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
             public void run() {






protected void onActivityResult(int requestCode, int resultCode, Intent data) {

 if (requestCode == 1 && resultCode == RESULT_OK) {
        //Bitmap photo = (Bitmap) data.getData().getPath(); 
        //Uri imagename=data.getData();
        Uri selectedImageUri = data.getData();
        imagepath = getPath(selectedImageUri);
        Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
        messageText.setText("Uploading file path:" +imagepath);

  public String getPath(Uri uri) {
         String[] projection = { MediaStore.Images.Media.DATA };
         Cursor cursor = managedQuery(uri, projection, null, null, null);
         int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
         return cursor.getString(column_index);

public int uploadFile(String sourceFileUri) {

    //sourceFileUri.replace(sourceFileUri, "ashifaq");

    int day, month, year;
    int second, minute, hour;
    GregorianCalendar date = new GregorianCalendar();

    day = date.get(Calendar.DAY_OF_MONTH);
    month = date.get(Calendar.MONTH);
    year = date.get(Calendar.YEAR);

    second = date.get(Calendar.SECOND);
    minute = date.get(Calendar.MINUTE);
    hour = date.get(Calendar.HOUR);

    String name=(hour+""+minute+""+second+""+day+""+(month+1)+""+year);
    String tag=name+".jpg";
    String fileName = sourceFileUri.replace(sourceFileUri,tag);

      HttpURLConnection conn = null;
      DataOutputStream dos = null;  
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024; 
      File sourceFile = new File(sourceFileUri); 

      if (!sourceFile.isFile()) {


        Log.e("uploadFile", "Source File not exist :"+imagepath);

        runOnUiThread(new Runnable() {
            public void run() {
             messageText.setText("Source File not exist :"+ imagepath);

        return 0;

        try { 

           // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection(); 
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName); 

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd); 
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                + fileName + "\"" + lineEnd);


            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available(); 

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead =, 0, bufferSize);  

            while (bytesRead > 0) {

              dos.write(buffer, 0, bufferSize);
              bytesAvailable = fileInputStream.available();
              bufferSize = Math.min(bytesAvailable, maxBufferSize);
              bytesRead =, 0, bufferSize);   


            // send multipart form data necesssary after file data...
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : " 
              + serverResponseMessage + ": " + serverResponseCode);

            if(serverResponseCode == 200){

                runOnUiThread(new Runnable() {
                     public void run() {
                      String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                              +" C:/wamp/wamp/www/uploads";
                         Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();

            //close the streams //

       } catch (MalformedURLException ex) {


           runOnUiThread(new Runnable() {
               public void run() {
                messageText.setText("MalformedURLException Exception : check script url.");
                Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();

           Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
       } catch (Exception e) {


           runOnUiThread(new Runnable() {
               public void run() {
                messageText.setText("Got Exception : see logcat ");
                   Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
           Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
       return serverResponseCode; 



Php Code


    $file_path = "uploads/";

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    $title =$_FILES['title'];
    //$descr=$file_path . basename( $_FILES['uploaded_file']['desc']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
$hostname_localhost ="localhost";
$database_localhost ="gcm";
$username_localhost ="root";
$password_localhost ="root";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
$time_offset ="525"; // Change this to your time zone
$time_a = ($time_offset * 120);
$time = date("h:i:s",time() + $time_a);
$date= date("d.m.y");
mysql_select_db($database_localhost, $localhost);

//$title = $_POST['title'];
//$title = $_POST['title'];

$query_search = "INSERT INTO images (name,title,descr, time, date)
VALUES ('$name','$title','$descr','$time','$date')";
$query_exec = mysql_query($query_search) 
or die(mysql_error());
echo "success";
  • Forum posts: 118

Nov 12, 2014 10:39:54 AM via Website

You've got two options. Both of them will do okay and serve their purpose. My first suggestion would be to use GET variables in your URL. It's also the easiest suggestion but not the most safe solution. Second suggestion would be to use a lilbrary to handle your desired requests at the same time. I'd recommend my second suggestion.

  1. GET variables.

Search for the following in your code:

URL url = new URL(upLoadServerUri);

Change it to the following:

String titleValue = title.getText().toString();
String descValue = desc.getText().toString();
int variablesAdded = 0;

if(titleValue != null && !titleValue.equals("")) {
    if(variablesAdded == 0)
        upLoadServerUri = upLoadServerUri + "?title=" + URLEncoder.encode(titleValue, "UTF-8");
        upLoadServerUri = upLoadServerUri + "&title=" + URLEncoder.encode(titleValue, "UTF-8");

if(descValue != null && !descValue.equals("")) {
    if(variablesAdded == 0)
        upLoadServerUri = upLoadServerUri + "?desc=" + URLEncoder.encode(descValue, "UTF-8");
        upLoadServerUri = upLoadServerUri + "&desc=" + URLEncoder.encode(descValue, "UTF-8");

URL url = new URL(upLoadServerUri);

What it does is adding GET variables to your existing URL. descValue and titleValue are values that are fetched from the EditText fields created by you. URLEncoder makes sure it gets encoded for URLs to prevent plain SQL Injection in your case.

In PHP you could simply get the variables by doing:

$title = $_GET["title"];
$desc = $_GET["desc"];
  1. For more information: Read these webpages.

Both are great solutions.

  • Forum posts: 17

Nov 12, 2014 11:06:03 AM via Website

Dear Kevin Berendsen,
Thank you so much for your effort, It is working perfectly.
You are really awesome.

  • Forum posts: 118

Nov 12, 2014 11:15:52 AM via Website

Hey Ashfaq, I'm glad to hear that it works :) Make sure you mark the topic as answered. Helps others who encounter the same issue and know that it can be solved by reading this topic.

The way to do that is to go to the first post. Move your mouse to the top right corner and click on "More" button. Select the option: "Set as Answered" :)

— modified on Nov 12, 2014 11:31:52 AM

  • Forum posts: 17

Nov 12, 2014 11:56:30 AM via Website

Dear Kevin,
If you don't mind,let me know how can i set maximum uploading image size while selecting from gallery itself ?
What changes i have to do for that purpose?

— modified on Nov 12, 2014 11:57:52 AM

  • Forum posts: 118

Nov 12, 2014 12:22:38 PM via Website

Search for the following in your code:

Bitmap bitmap=BitmapFactory.decodeFile(imagepath);

Add a white line under it and add the following:

int sizeInBytes = 0;
int MAX_BYTES = your_number_of_bytes;

    sizeInBytes = bitmap.getRowBytes() * bitmap.getHeight();
} else {
    sizeInBytes = bitmap.getByteCount();

if(sizeInBytes > MAX_BYTES) {
    // If the image is higher than max number of bytes, start all over again.

Use a converter to convert MBs into bytes and set your own maximum file size. Just Google for it. Keep in mind that PHP has it's own limit. I'm not sure if it works though but according to people on Stackoverflow, it does :)

Edit: I don't know how to do that while selecting an image in the gallery selection screen.

— modified on Nov 12, 2014 12:25:25 PM

  • Forum posts: 17

Nov 13, 2014 5:36:59 AM via Website

Thanks a lot for your efforts,
Will try that code :)

— modified on Nov 13, 2014 5:51:50 AM

  • Forum posts: 3

Mar 29, 2015 1:55:20 PM via Website

hi, ashfaq is it possible to send me ( the full code(Android image and data uploading to server from gallery). i am new on android and trying to be a developer like you. thanks.

  • Forum posts: 3

Mar 29, 2015 1:57:23 PM via Website

hi, kevin is it possible to send me ( the full code(Android image and data uploading to server from gallery). i am new on android and trying to be a developer like you. thanks.

  • Forum posts: 3

Mar 30, 2015 8:17:04 AM via Website

i cant post my code here. but i tried with your code but no result. i can only image upload but not data like name. pls. help me in this code. thanks.

  • Forum posts: 1

Mar 18, 2016 12:15:09 PM via Website

hey Ashfaq is it possible to send me the full code(Android image and data uploading to server from gallery) at ( i am trying that have some issues. Thanks.

  • Forum posts: 1

Oct 31, 2016 7:49:20 PM via Website

hy ishfaq plz i am working on my final year project please can u send me code

i need this

  • Forum posts: 1

Mar 8, 2017 4:53:03 PM via Website

Hey Keivn do you have an email if so may you please tell me because i have question to ask.