title: Android Image Upload to php server base64 not working
body: <p>I am trying to upload an image from gallery to my local php server with the Base64 method. Code gives no error and everything seems fine, the mysql entry for the record is going through but the image is not saving.</p>
  
  <p><em>By pressing this button i am getting the image by intent</em>
  <strong>android code</strong></p>
  
  <pre><code>public void uploadImageButtonFunction(View view){
  
      Intent intent = new Intent();
      // Show only images, no videos or anything else
      intent.setType("image/*");
      intent.setAction(Intent.ACTION_GET_CONTENT);
      // Always show the chooser (if there are multiple options available)
      startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
  }
  </code></pre>
  
  <p><strong><em>This just opens the gallery for image picking by pressing a button</em></strong>
  After pressing that button and picking the image here where we receive the image</p>
  
  <pre><code>@Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
  
          if (requestCode == PICK_IMAGE_REQUEST &amp;&amp; resultCode == RESULT_OK &amp;&amp; data != null &amp;&amp; data.getData() != null) {
  
              filepathUri = data.getData();
  
              try {
                  bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filepathUri);
                  // Log.d(TAG, String.valueOf(bitmap));
                  String s = getRealPathFromURI(filepathUri);
                  Log.i("imagepath", s);
                  textView.setText(s.split("/")[s.split("/").length - 1]);
  
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
  </code></pre>
  
  <p><em>Just assigning to a <strong>bitmap</strong> we declared in the class variable.</em></p>
  
  <pre><code>public String getRealPathFromURI(Uri uri) {
      String[] projection = {MediaStore.MediaColumns.DATA};
      Cursor cursor = managedQuery(uri, projection, null, null, null);
      int column_index = cursor
              .getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
      cursor.moveToFirst();
      String imagePath = cursor.getString(column_index);
  
      return imagePath;
  }
  </code></pre>
  
  <p>*This method gets the <strong><em>PATH</em></strong> of the image from the uri, the uri is declared globally as class variable*</p>
  
  <p><strong><em>now this function converts the bitmap to Base64 string</em></strong></p>
  
  <pre><code> private String imageToString(Bitmap bitmap){
  
          ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
          bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
          byte[] imBytes = byteArrayOutputStream.toByteArray();
          return Base64.encodeToString(imBytes, Base64.DEFAULT);
      }
  </code></pre>
  
  <p>this what uploads it to the php server with <strong><em>POST request with volley library</em></strong></p>
  
  <pre><code>private void uploadImageBase64(){
  
  StringRequest stringRequest = new StringRequest(Request.Method.POST, signUpUrl,
          new Response.Listener&lt;String&gt;() {
              @Override
              public void onResponse(String response) {
  
  
                  try {
  
                      name.setText("");
                      number.setText("");
                      textView.setText("");
  
                      Log.i("resp", response);
                      Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
  
                  }catch (Exception e){
                      Toast.makeText(Insert.this, e.getMessage(), Toast.LENGTH_LONG).show();
                      e.printStackTrace();
                  }
  
  
              }
          }, new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
  
          Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
  
      }
  })
  
  
  {
  
  
      @Override
      protected Map&lt;String, String&gt; getParams() throws AuthFailureError {
  
          Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
          params.put("name", name.getText().toString().trim());
          params.put("number", number.getText().toString().trim());
          params.put("image", imageToString(bitmap));
  
          return params;
      }
  };
  
  MySingleton.getInstance(Insert.this).addToRequestQueue(stringRequest);
  
  
  }
  </code></pre>
  
  <p><strong><em>and i copied the MySingleton class from volley documentation</em></strong></p>
  
  <p><em>here it is if you need it</em></p>
  
  <pre><code>package com.example.slimshady.whatsappclone;
  
  import android.content.Context;
  import android.graphics.Bitmap;
  import android.util.LruCache;
  
  import com.android.volley.Request;
  import com.android.volley.RequestQueue;
  import com.android.volley.toolbox.ImageLoader;
  import com.android.volley.toolbox.Volley;
  
  public class MySingleton {
      private static MySingleton mInstance;
      private RequestQueue mRequestQueue;
      private ImageLoader mImageLoader;
      private static Context mCtx;
  
      MySingleton(){}
  
      private MySingleton(Context context) {
          mCtx = context;
          mRequestQueue = getRequestQueue();
  
          mImageLoader = new ImageLoader(mRequestQueue,
                  new ImageLoader.ImageCache() {
                      private final LruCache&lt;String, Bitmap&gt;
                              cache = new LruCache&lt;String, Bitmap&gt;(20);
  
                      @Override
                      public Bitmap getBitmap(String url) {
                          return cache.get(url);
                      }
  
                      @Override
                      public void putBitmap(String url, Bitmap bitmap) {
                          cache.put(url, bitmap);
                      }
                  });
      }
  
      public static synchronized MySingleton getInstance(Context context) {
          if (mInstance == null) {
              mInstance = new MySingleton(context);
          }
          return mInstance;
      }
  
      public RequestQueue getRequestQueue() {
          if (mRequestQueue == null) {
              // getApplicationContext() is key, it keeps you from leaking the
              // Activity or BroadcastReceiver if someone passes one in.
              mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
          }
          return mRequestQueue;
      }
  
      public &lt;T&gt; void addToRequestQueue(Request&lt;T&gt; req) {
          getRequestQueue().add(req);
      }
  
      public ImageLoader getImageLoader() {
          return mImageLoader;
      }
  }
  </code></pre>
  
  <p><strong><em>now for the php side
  sim enough code, i am using wamp server</em></strong></p>
  
  <p><strong>PHP CODE</strong></p>
  
  <pre><code>&lt;?php
  
  $conn=mysqli_connect("localhost","root","", "shady") or die("Unable to connect");
  
  $name = $_POST["name"];
  $number = $_POST["number"];
  $image = $_POST["image"];
  
  $upload_path = "android_pool/whatsapp/images/$name.jpg"; // String concatination happening here between the $name variable and the .jpg string
  $imagelink = "http://1.0.0.2/android_pool/whatsapp/images/$name.jpg";
  
  if(mysqli_connect_error($conn)) {
      echo "Failed To Connect";
  }
  
  $qry = "INSERT INTO contacts (`name`, `number`, `imagelink`) VALUES('$name', '$number', '$imagelink')";
  
  $res = mysqli_query($conn, $qry);
  
  if ($res) {
  
  
      file_put_contents($upload_path, base64_decode($image));
  
      echo $image;
  
      echo json_encode(array('response'=&gt;'image Uploaded'));
  
  
  }else{
      echo json_encode(array('response'=&gt;'image not uploaded'));
  }
  
  
  mysqli_close($conn);        
  
  
  ?&gt;
  </code></pre>
  
  <p><strong><em>records are getting inserted but no images present in the folder</em></strong>
  <strong>Look at the "jojo" record it is inserted but no image uploaded for it</strong>
  <a href="https://i.stack.imgur.com/qCBts.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qCBts.png" alt="enter image description here"></a></p>
  
  <p><strong>the images folder does not contain the jojo.jpg</strong>
  <a href="https://i.stack.imgur.com/lvoMx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lvoMx.png" alt="enter image description here"></a></p>
  
  <p><strong>So what am i doing wrong here ? and is there a better way to achieve what i am trying to do ?</strong></p>
  
  <p>Edit 1:</p>
  
  <p><strong>The Five Images Are Inserted Manually, There Should Be A Jojo.jpg In This Folder Which Is Not Present, But Record Of That Is Present In The Mysql&lt; As Shown In The Image</strong></p>