title: Uploading image to php server from android
body: <p>This is my android client code which sends a file from the android gallery to the php server:</p>
  
  <pre><code>package com.example.upload;
  
  import java.io.DataInputStream;
  import java.io.DataOutputStream;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.net.HttpURLConnection;
  import java.net.URL;
  
  import com.loopj.android.http.RequestParams;
  
  import android.support.v7.app.ActionBarActivity;
  import android.content.Intent;
  import android.database.Cursor;
  import android.graphics.BitmapFactory;
  import android.net.Uri;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.provider.MediaStore;
  import android.util.Log;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.view.View;
  import android.widget.Button;
  import android.widget.ImageView;
  import android.widget.Toast;
  
  
  public class MainActivity extends ActionBarActivity {
  
      private static int RESULT_LOAD_IMG = 1;
      String imgPath, fileName;
      RequestParams params = new RequestParams();
      String urlServer = "http://url.com/abc.php";
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary =  "*****";
      HttpURLConnection connection = null;
      DataOutputStream outputStream = null;
      DataInputStream inputStream = null;
      int serverResponseCode;
      String serverResponseMessage;
      FileInputStream fileInputStream;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          Button load = (Button)findViewById(R.id.buttonLoadPicture);
          load.setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  // TODO Auto-generated method stub
                  // Create intent to Open Image applications like Gallery, Google Photos
                  Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                          android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                  // Start the Intent
                  startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
              }
          });
  
  
  
      }
  
   // When Image is selected from Gallery
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          try {
              // When an Image is picked
              if (requestCode == RESULT_LOAD_IMG &amp;&amp; resultCode == RESULT_OK
                      &amp;&amp; null != data) {
                  // Get the Image from data
  
                  Uri selectedImage = data.getData();
                  String[] filePathColumn = { MediaStore.Images.Media.DATA };
  
                  // Get the cursor
                  Cursor cursor = getContentResolver().query(selectedImage,
                          filePathColumn, null, null, null);
                  // Move to first row
                  cursor.moveToFirst();
  
                  int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                  imgPath = cursor.getString(columnIndex);
                  cursor.close();
                  ImageView imgView = (ImageView) findViewById(R.id.imgView);
                  // Set the Image in ImageView
                  imgView.setImageBitmap(BitmapFactory
                          .decodeFile(imgPath));
                  Log.v("imgPath", imgPath);
  
                  uploadImage();
  
              } else {
                  Toast.makeText(this, "You haven't picked Image",
                          Toast.LENGTH_LONG).show();
              }
          } catch (Exception e) {
              Toast.makeText(this, "Something went wrong" + e, Toast.LENGTH_LONG)
                      .show();
              Log.v("Error",e.toString());
          }
  
      }
  
      private void uploadImage() {
          // TODO Auto-generated method stub
          new AsyncTask&lt;Void, Void, String&gt;() {
  
              protected void onPreExecute() {
                  try {
                      fileInputStream = new FileInputStream(new File(imgPath));
                  } catch (FileNotFoundException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              };
  
              @Override
              protected String doInBackground(Void... params) {
                  // TODO Auto-generated method stub
  
                  int bytesRead, bytesAvailable, bufferSize;
                  byte[] buffer;
                  int maxBufferSize = 1*1024*1024;
  
                  try
                  {
  
                      URL url = new URL(urlServer);
                      connection = (HttpURLConnection) url.openConnection();
  
                      // Allow Inputs &amp;amp; Outputs.
                      connection.setDoInput(true);
                      connection.setDoOutput(true);
                      connection.setUseCaches(false);
  
                      // Set HTTP method to POST.
                      connection.setRequestMethod("POST");
  
                      connection.setRequestProperty("Connection", "Keep-Alive");
                      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
  
                      outputStream = new DataOutputStream( connection.getOutputStream() );
                      outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                      outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + imgPath +"\"" + lineEnd);
                      outputStream.writeBytes(lineEnd);
  
                      bytesAvailable = fileInputStream.available();
                      bufferSize = Math.min(bytesAvailable, maxBufferSize);
                      buffer = new byte[bufferSize];
  
                      // Read file
                      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  
                      while (bytesRead &gt; 0)
                      {
                          outputStream.write(buffer, 0, bufferSize);
                          bytesAvailable = fileInputStream.available();
                          bufferSize = Math.min(bytesAvailable, maxBufferSize);
                          bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                      }
  
                      outputStream.writeBytes(lineEnd);
                      outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
  
                      // Responses from the server (code and message)
                      serverResponseCode = connection.getResponseCode();
                      serverResponseMessage = connection.getResponseMessage();
  
                      Log.v("Response Message",serverResponseMessage);
  
                      fileInputStream.close();
                      outputStream.flush();
                      outputStream.close();
                  }
                  catch (Exception ex)
                  {
                      //Exception handling
                      Log.v("Error",ex.toString());
                  }
  
                  return serverResponseMessage;
              }
  
              @Override
              protected void onPostExecute(String msg) {
                  Toast.makeText(getApplicationContext(), "Successful" + serverResponseCode, Toast.LENGTH_LONG).show();;
              }
  
          }.execute(null,null,null);
  
      }
  
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
      }
  
      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          // Handle action bar item clicks here. The action bar will
          // automatically handle clicks on the Home/Up button, so long
          // as you specify a parent activity in AndroidManifest.xml.
          int id = item.getItemId();
          if (id == R.id.action_settings) {
              return true;
          }
          return super.onOptionsItemSelected(item);
      }
  }
  </code></pre>
  
  <p>This is my PHP Code:</p>
  
  <pre><code>&lt;?php
  $target_path  = "uploadedimages/";
  $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
  if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
  {
      echo "The file ".  basename( $_FILES['uploadedfile']['name']).
   " has been uploaded";
  } 
  else
  {
      echo "There was an error uploading the file, please try again!";
  }
  ?&gt;
  </code></pre>
  
  <p>I am trying to upload an image from my android client to the php server. The server response message gives me ok. The server status code also gives 200. So, A valid http connection is being built. Still, the image file does not get uploaded onto my domain. Logcat also does not log any error. I am confused as to where I am going wrong. Any help would be appreciated.</p>