0

i am trying to upload image using volley lib . am pretty sure that am able to convert my image to string and send it to server side.. because when I "echo" the 'image' from server side. I receive the same string as response. but when I am using the php the following code to decode the string image and upload it to database ... I get a file name in "img" coloumn of my database without any extension.(see the image link below to understand what am trying to say) I'll upload my various files (mainACtivity, php database image, and upload.php file and image in the string form) below.

Most probably the fault is in the PHP side.. I am just not able to figure it out. being a java developer.(don't have much understanding of the php code) Help me out in that. and let me know if there's something wrong in my Java file.

PS: sorry for bad English

my upload.php file

 <?php
    $host="localhost"; //replace with database hostname 
    $username="xxxx"; //replace with database username 
    $password="xxxx"; //replace with database password 
    $db_name="snapcash"; //replace with database name

    $con=mysql_connect($host,$username,$password);
    $db=mysql_select_db($db_name);

    if($_SERVER['REQUEST_METHOD']=='POST'){

    $image = $_POST['image'];
    $name = $_POST['name'];

    //require_once('dbConnect.php');

    $sql ="SELECT id_img FROM image ORDER BY id_img ASC";

    $res = mysqli_query($con,$sql);

    $id = 0;

    while($row = mysqli_fetch_array($res)){
    $id = $row['id'];
 }

 $path = "images/$id.png";

 $actualpath = "ec2-54-191-118-200.us-west-2.compute.amazonaws.com/$path";

 $sql = "INSERT INTO image (photo,name) VALUES ('$actualpath','$name')";

 if(mysqli_query($con,$sql)){
     file_put_contents($path,base64_decode($image));
     echo "Successfully Uploaded";  //this never echos :(
 }
 else{
     echo "$image"  // am receiveing this echo i.e. the image in string form
 }

mysqli_close($con);

 }else{
     echo "Error";
 }
?>

MainActivity.java

package absdevelopers.com.volleyuploadimage;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button buttonChoose;
private Button buttonUpload;

private ImageView imageView;

private EditText editTextName;

private Bitmap bitmap;

private int PICK_IMAGE_REQUEST = 1;

private String UPLOAD_URL = "http://ec2-54-191-118-200.us-west-2.compute.amazonaws.com/img1.php";

private String KEY_IMAGE = "image";
private String KEY_NAME = "name";


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

    buttonChoose = (Button) findViewById(R.id.buttonChoose);
    buttonUpload = (Button) findViewById(R.id.buttonUpload);

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

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

    buttonChoose.setOnClickListener(this);
    buttonUpload.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    if (v == buttonChoose) {
        showFileChooser();
    }

    if(v == buttonUpload){
        uploadImage();
    }


}

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {
            //Getting the Bitmap from Gallery
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            //Setting the Bitmap to ImageView
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public String getStringImage(Bitmap bmp) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

private void uploadImage(){
    //Showing the progress dialog
    final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(MainActivity.this, response , Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();

                    //Showing toast
                    Toast.makeText(MainActivity.this, "volley Error", Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(bitmap);
            Log.i("hello",image);

            //Getting Image Name
            String name = editTextName.getText().toString().trim();

            //Creating parameters
            Map<String,String> params = new Hashtable<>();

            //Adding parameters
            params.put(KEY_IMAGE, image);
            params.put(KEY_NAME, name);

            //returning parameters
            return params;
        }
    };

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}


 }

databse image

This is my databse image please check it out

the string that am generating on the java(android) side its different for different images

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                      AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
                                                                      AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAEgAgADASIA
                                                                      AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
                                                                      AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
                                                                      ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
                                                                      p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
                                                                      AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
                                                                      BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
                                                                      U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
                                                                      uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD/AD/6
                                                                      KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAoo
                                                                      ooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiii
                                                                      gAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKA
                                                                      CiiigAooooAKKKKACiiigAoqxViCxuLjPb+vLdfXgE47E9ck0AZ9WPI9/wBf/sa7eD4c+Op5fs48
                                                                      K69n20Vs9W9vbcOc9eOprmhB9hmNtf291m0vAL2zPp8wB9jhec9QRyTkgAzPJm9/zNHkze/5mvq7
                                                                      4+fAG6+EfxW8O/Cy/t9V0LUvENl4Qb7Hq+T9hbXmcYbrxs/sVuR03ZJwK4HxH4J1PwZ4S8T+HvFu
                                                                      k3nhjx54V8YaRe32i6vZNpurDR9d0JyqENjA3qHwDgLypDZBAPCKKtXUE8MjLP8Ae9fX5m9+OevX
                                                                      jGSTiqtABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRR
                                                                      QAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFWr
                                                                      PyPMPn/d4x9dzev4/wBP4qAGeTN7/matD7RPn/j6PT26Fv8AH6dO4OfoH4Q+Kfg5oRkPjTw/qGq6
                                                                      iCRZNc2K6kljgsMoo2kL7BAQGUkDv9HeFPF/7JGu/Enw3qeq2+laDpg/tUa3aax4JH/CJ35JfHy7
                                                                      i2Dg5zxnGTuOCAfC2heHfEV+SbHw/d3dvkD7WdGLY+ZuckEYOB0YnHJ55b9Jvgj+yr+0d4kh8N+I
                                                                      YPgFql1/wj17/wASTWcHTO7c9D4V8Tev4jB+9n9ufgt+yf8ABr4kaz4I1D4Q6d4N8Zabq2ii/vbz
                                                                      /iRanqx1fLcHw/j3+uOxBxX9F37Hn7FmjaFNpviHxz4d/szRfDoFhZeDrPRP+QfyfQH6duo6lTQB
                                                                      +Hn7D/8AwSg/au8Ra+fiF4t/Z78TjTdXvlA0a00TQdT1aw8JFmAA8Qlf+EWy2BgAkk44zy3x7/wV
                                                                      i/4JJ658Nvh/+0x8cvDWgabaeIfg34o8JeLvFF1Zsw1TUfh14jE0b8AYz4NRNBUn7zKxBYqDX+l3
                                                                      q+ufCv4J+E9duILjTNLtdJsRf3tnZ3w/tXUCGbjqDz+PGckE8/yc/wDBRvxH4E/aC8AeMdG8C/tx
                                                                      Wnwk0XxXrXi3wj41+G2sa3oep+E/GA18ynxDoPiHxBn249sjsSQD8jPGvhv9jn/gqB/wUJ/4JLeH
                                                                      r7xXp/g3TfiX+yBql3qHiXRzbSNqP7RngNLrxB4e8B64GMkjRjxJoLeEm8KQ7vHKOYPh1I4m+xuf
                                                                      p/8A4LOf8E//AIfftf8A/BNdP2yfhjoulW37Wn7Ca6P8JPjzpGkKx1T4m/Cbw3J/wj8bgeYP3vgz
                                                                      w2X8VCTafLt9G8bqE3tl/wAZ9M/Yf8e/se+Mvhb4x+JHx/8AB2l2vwH8f6r8WPgreeDvFJ1PVvEX
                                                                      g8N4ZPiDXfAHI/4RrxKPE0a4GcD4gKvdcn+23wX8BPAfxv8A+CUPxJ8Y/Bv4hnVB4w+Bni74k2Hi
                                                                      ay0/RdN1b4oaWfAPifxEnh/4x7UbxR4jVhr5G+R1XeyIMu6mgD/KL1VdEbwfoV8lyx8Q/a9Usb+0
                                                                      PVdICFtEbAGNq7SR1JXGSSc159X0Z8dvhz4q8KeIxr+peH7rSvDni6PSb7w3fLZumk6gH8DeG/EG
                                                                      NEY8NHt14Nhflwy5y6vXznQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUU
                                                                      AFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQA
                                                                      UUUUAFFFFABWhZQG4mNt245692zj6/jkbvRs59Twf64/U/8AoVAH3f8AB79hXxt8X4bbUrDx34C0
                                                                      DT7oqbo3Wtf2j/ZZDMwOuBAFTJJPyjryAGBNe+aB/wAEofjN4y+Imm+DfBus/wBqaJdXg0//AITE
                                                                      aFri6Q2rBy2NBAQF+cEFiSOOuMj2r9hnxv4FttavPBlzrBGjXOjaPp9n4kOtaECCG8UDBB6HOvc5
                                                                      5zoJBBIr+jb9kP44/Ar4cab4n06+8ZaXpem/8Ta/vftn/IWPPin/AJmDP/QteHvfAI6AcgH8pfg7
                                                                      9l39sj9n74o2/h3wn4h13wZ4kutaGn2V7o2ia9qmeW558J4BwpAA468Arz/Wf/wTW8K/t9ftLaBd
                                                                      /Av9rv4qfFC6Hh7+x/8AhFvGNnrg8C6Vp/hDd4nH9gHw/wCG/CX/AAlR48P8kDqQNoPNfSP7Bng7
                                                                      9nn9pb44/ET4hX+o2vjLxZpN6P8Alx/sv+0NXJP/AAkPYn/hGfBf/CPaB+pyc5r90/gN8MNF+Cnx
                                                                      RuvGMFtdW2m6tov2+zvL0Z1bUR/YHiYYPHf/AIkHfjuSaAPxY/aK/wCCT3jLVtSu/AtjrWvXXhP+
                                                                      xft9jrP2HXfDH9oAFwP+Eg8P7e/H4YzgYr+Z/wD4LB/8EofFH7K/gPXvFmr+KbbxB4k8D3Wl67rV
                                                                      mtpr8ZXwn4h12dY5A3iIA/u2Ik28B/8AVsSpav8ASX+Efxb8K/FbWfHXjLSbnS7X7JZ6PYWP9sH/
                                                                      AJB45/4SHqSev484yAXr+Yr/AILY+B9O/ak+OHwP+Gl7qOg2vwVx/wALZ/ag8Ykf2cPD3wM8A+IJ
                                                                      fEPh7QTuJGfjP4k8Q6ER4RPO7QQwbcN1AH88ngn/AIJo+KP2u/8Aglp4e/at8L/ELxVqXiD4JWek
                                                                      a94z8AM39raXqHg7f4nOv67oLrGo8OEeGQpbwiFQFtfB2qMgf1If8G/F98LD+xtovg/V/EVqbf4e
                                                                      +GdI8B+Kf7ZvR/a1h4S1/Qc+v/Isnv7jGf4j4j/wTc/bM/YW/Zo/4Jsfteah458ZaB4Y8FeLrP4i
                                                                      3/w+8NazohGleIPCGgeH28O+HtB8O/8AQ0HIHBOMbvmyMH+TrwP/AMFZvFn7Kfx1g+In7JK6ZoWl
                                                                      3Tare634c8SXuvf2PqGk/Pjw/wCIdB3AZKpuAJztJGTgmgD9iP8AguV/wTK8B/Db
Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43
lol
  • 47
  • 9
  • Do you get anywhere by putting `echo "In here";` after your mysqli query conditional to check that the `if` part works before you try to encode the string? If you see the string it suggests something is wrong with the mysqli. Otherwise does `echo base64_decode($image);` where you currently have `echo $image;` produce anything? Do you get anything from `echo $actualpath;` ? – Steve Apr 02 '16 at 02:10
  • Also try `$path = "images/$id" . '.png';` to avoid the dot being mistaken for concatenation - the dot seems to appear in your image name but the `png` does not. Use single quotes for the `'.png'` The dot in between should join the two parts of the file path/name/type together. – Steve Apr 02 '16 at 02:35
  • Not sure if it matters but in your Java you have `bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);` - should that be something like `bmp.compress(Bitmap.CompressFormat.PNG, 100, out);` Not sure if this might be any use http://stackoverflow.com/questions/8417034/how-to-make-bitmap-compress-without-change-the-bitmap-size – Steve Apr 02 '16 at 02:58
  • @Steve THank you very much for taking your time and replying :) for your **first** question - I do not get "in here" when I echo it inside if() condition... **second**- when I "echo $image" I get the string that I sent from my application . **third**- if I echo base64_decode($image), I get random strings which I don't even understand .. and don't even know if they are string...**fourth** didn't try echo $actualpath.. – lol Apr 02 '16 at 04:42
  • what might be wrong in mysqli_query condition? – lol Apr 02 '16 at 04:43
  • I don't know but if you never get into the `if` then there would be something wrong either with the connection script or one of the variables that make up the `$sql` part of the query which is why I thought echoing `$actualpath` might reveal if it is blank, for example. Put the echoed message just after the first line - if it doesn't appear you know it never gets that far - it shouldn't, because you are getting the other `echo $image` so the condition is not being met I would say. `if(mysqli_query($con,$sql)){` is not working it would seem. – Steve Apr 02 '16 at 06:02
  • Just noticed `$con=mysql_connect` should that be `mysqli` likewise for `$db=mysql_select_db($db_name);`? – Steve Apr 02 '16 at 06:12
  • thank you :) I am working on it . – lol Apr 02 '16 at 13:46
  • You might find these handy tools for checking your output and encoding/decoding to compare one with another http://www.base64-image.net/ and http://www.freeformatter.com/base64-encoder.html Did using `$path = "images/$id" . '.png';` make any difference? – Steve Apr 03 '16 at 00:10
  • yeah that worked :) and thanks for helping. my images are uploaded and decoded perfectly – lol Apr 03 '16 at 12:35
  • Glad to hear that - well done! – Steve Apr 05 '16 at 18:58

1 Answers1

2

try this code in the PHP side

<?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password=""; //replace with database password 
$db_name="mydb"; //replace with database name

$con=mysql_connect($host,$username,$password);
$db=mysql_select_db($db_name);

 $name = $_REQUEST['name']; //image name
 $image = $_REQUEST['image']; //image in string format
 $user=$_REQUEST['User_ID'];

 $decodedImage = base64_decode($image);
 $image_file=time().rand(1111,9999);
 $name=$name.$image_file;

 $base_path='/var/www/html/uploads/';

    file_put_contents($base_path.$name.".jpg", $decodedImage);

         mysql_query("INSERT into `image`(`img`,`User_ID`,`date`) values ('".$image_file.".jpg','$user',now() )");
      echo mysql_insert_id();
?>
Bawa
  • 876
  • 10
  • 28