Android image uploading to server from gallery

  • Replies:15
  • Answered
Ashfaq
  • 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.io.DataOutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
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;
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    uploadButton = (Button)findViewById(R.id.uploadButton);
    btnselectpic = (Button)findViewById(R.id.button_selectpic);
    messageText  = (TextView)findViewById(R.id.messageText);
    imageview = (ImageView)findViewById(R.id.imageView_pic);
    title=(EditText)findViewById(R.id.ettittle);
    desc=(EditText)findViewById(R.id.etdesc);

    btnselectpic.setOnClickListener(this);
    uploadButton.setOnClickListener(this);
    upLoadServerUri = "192.168.2.7/news/upload.php";
    ImageView img= new ImageView(this);

}


@Override

public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {

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

                  uploadFile(imagepath);

             }
           }).start();     

}

}

@Override

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);
        imageview.setImageBitmap(bitmap);
        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);
         cursor.moveToFirst();
         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()) {

        dialog.dismiss(); 

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

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

        return 0;

      }
      else
      {
        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.setRequestMethod("POST");
            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);

            dos.writeBytes(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 = fileInputStream.read(buffer, 0, bufferSize);  

            while (bytesRead > 0) {

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

             }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            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";
                      messageText.setText(msg);
                         Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                     }
                 });                
            }    

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

       } catch (MalformedURLException ex) {

           dialog.dismiss();  
           ex.printStackTrace();

           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) {

           dialog.dismiss();  
           e.printStackTrace();

           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);  
       }
       dialog.dismiss();       
       return serverResponseCode; 

       } 
     }

}

Php Code

    <?php

    $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";
    }
    $name=$_FILES['uploaded_file']['name'];
$hostname_localhost ="localhost";
$database_localhost ="gcm";
$username_localhost ="root";
$password_localhost ="root";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
$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'];
//$desc=$_POST['desc'];
//$title = $_POST['title'];
//$desc=$_POST['desc'];

$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";
 ?>

Reply
Kevin Berendsen
  • 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");
    else
        upLoadServerUri = upLoadServerUri + "&title=" + URLEncoder.encode(titleValue, "UTF-8");
    variablesAdded++;
}

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

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.
    http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk
    https://square.github.io/retrofit/

Both are great solutions.

Ashfaq

Reply
Ashfaq
  • 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.

Reply
Kevin Berendsen
  • 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

Ashfaq

Reply
Ashfaq
  • 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

Reply
Kevin Berendsen
  • 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;

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
    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

Ashfaq

Reply
Ashfaq
  • 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

Reply
azizul khan
  • Forum posts: 3

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

hi, ashfaq is it possible to send me (azizulkhn@yahoo.com) 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.
azizul

Reply
azizul khan
  • Forum posts: 3

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

hi, kevin is it possible to send me (azizulkhn@yahoo.com) 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.
azizul

Reply
azizul khan
  • 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.

Somi Rana

Reply
Khadija Saleem
  • 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 (khadijasaleem027@gmail.com). i am trying that have some issues. Thanks.

Somi Rana

Reply
Somi Rana
  • 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
ranaawaisse142@gmail.com

Reply
Nate letang
  • 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.

Reply
Abdulkadir
  • Forum posts: 1

Jun 23, 2017, 1:51:11 AM via Website

Please send me that code i need this so much thanks

Reply
Radha
  • Forum posts: 1

Feb 6, 2019, 10:48:29 AM via Website

uploadFile: HTTP Response is : Not Found: 404

Actually Server side code is in .net. I need to upload image from gallery and some related data to the server.
Could you please help me.

Reply
CarlineBurch
  • Forum posts: 18

Apr 8, 2019, 1:20:54 PM via Website

My first suggestion would be to use GET variables in your URL. It's also the easiest suggestion but not the most safe solution.

Reply