title: Upload image in jpeg format in multipart file on server in android
body: <p>hi i am developing an application that needs to post some images in jpeg format to server in multi-part file form , i have written below given code for this but it gives  following response, </p>
  
  <pre><code>01-15 00:32:14.119: I/System.out(7598): file is upload {"status":"error","message":"Please, Specify valid Parameter for file"}
  </code></pre>
  
  <p>please someone help me. Thanks in advance .
  Here is my activity code</p>
  
  <pre><code>public class SendPostActivity extends Activity implements OnClickListener {
      private Context appContext;
      private String messageType;
      HashMap&lt;String, String&gt; fileList = new HashMap&lt;String, String&gt;();
      public String finalImagePath = null;
      // number of images to select
      private static final int PICK_IMAGE = 1;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          // TODO Auto-generated method stub
          super.onCreate(savedInstanceState);
          overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
          setContentView(R.layout.activity_send_post);
          overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
  
          appContext = this;
          initComponent();
      }
  
      private void initComponent() {
  
          ((Button) findViewById(R.id.btnLeftNav)).setVisibility(View.VISIBLE);
          ((Button) findViewById(R.id.btnRightNav)).setVisibility(View.VISIBLE);
          ((Button) findViewById(R.id.btnRightNav))
                  .setBackgroundResource(R.drawable.send_btn);
          ((Button) findViewById(R.id.btnLeftNav)).setOnClickListener(this);
          ((Button) findViewById(R.id.btnRightNav)).setOnClickListener(this);
          ((ImageView) findViewById(R.id.imageviewCamera))
                  .setOnClickListener(this);
          ((ImageView) findViewById(R.id.imageviewGallery))
                  .setOnClickListener(this);
          ((TextView) findViewById(R.id.txtAudioSong)).setOnClickListener(this);
          ((TextView) findViewById(R.id.txtVedioSong)).setOnClickListener(this);
  
          Typeface face = Typeface.createFromAsset(getAssets(),
                  "fonts/GeosansLight.ttf");
          ((TextView) findViewById(R.id.txtHeading)).setTypeface(face);
          ((EditText) findViewById(R.id.edtMessage)).setTypeface(face);
          ((TextView) findViewById(R.id.txtHeading)).setText("Send Post");
  
      }
  
      @Override
      public void finish() {
          super.finish();
          overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
      }
  
      @Override
      public void onClick(View v) {
          // TODO Auto-generated method stub
          if (v.getId() == R.id.btnLeftNav) {
              this.finish();
          } else if (v.getId() == R.id.btnRightNav) {
              String strPostMessage = ((EditText) findViewById(R.id.edtMessage))
                      .getEditableText().toString().trim();
              if (strPostMessage.length() == 0) {
                  Toast.makeText(appContext, "Type message.", Toast.LENGTH_LONG)
                          .show();
              } else {
                  messageType = "text";
  
              }
  
          }
          // on this button click i want to post images to server
          else if (v.getId() == R.id.imageviewCamera) {
              Intent cameraIntent = new Intent(
                      android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
              startActivityForResult(cameraIntent, 1);
          } else if (v.getId() == R.id.imageviewGallery) {
              /*
               * Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
               * intent.setType("image/*"); startActivityForResult(intent, 2);
               */
              selectImageFromGallery();
          } else if (v.getId() == R.id.txtAudioSong) {
              Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
              intent.setType("audio/*");
              startActivityForResult(intent, 3);
          } else if (v.getId() == R.id.txtVedioSong) {
              Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
              intent.setType("video/*");
              startActivityForResult(intent, 4);
          }
      }
  
  
  
      public String getRealPathFromURI(Context context, Uri contentUri) {
          Cursor cursor = null;
          try {
              String[] proj = { MediaStore.Images.Media.DATA };
              cursor = context.getContentResolver().query(contentUri, proj, null,
                      null, null);
              int column_index = cursor
                      .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
              cursor.moveToFirst();
              return cursor.getString(column_index);
          } finally {
              if (cursor != null) {
                  cursor.close();
              }
          }
      }
  
  
      public void selectImageFromGallery() {
          Intent intent = new Intent();
          intent.setType("image/*");
          intent.setAction(Intent.ACTION_GET_CONTENT);
          startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                  PICK_IMAGE);
      }
  
      public void decodeFile(String filePath) {
          // Decode image size
          BitmapFactory.Options o = new BitmapFactory.Options();
          o.inJustDecodeBounds = true;
          BitmapFactory.decodeFile(filePath, o);
  
          // The new size we want to scale to
          final int REQUIRED_SIZE = 1024;
  
          // Find the correct scale value. It should be the power of 2.
          int width_tmp = o.outWidth, height_tmp = o.outHeight;
          int scale = 1;
          while (true) {
              if (width_tmp &lt; REQUIRED_SIZE &amp;&amp; height_tmp &lt; REQUIRED_SIZE)
                  break;
              width_tmp /= 2;
              height_tmp /= 2;
              scale *= 2;
          }
  
          // Decode with inSampleSize
          BitmapFactory.Options o2 = new BitmapFactory.Options();
          o2.inSampleSize = scale;
          bitmap = BitmapFactory.decodeFile(filePath, o2);
          if (bitmap != null) {
              new ImageUploadTask().execute();
          }
  
      }
  
      private Bitmap bitmap;
  
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
  
          if (requestCode == PICK_IMAGE &amp;&amp; resultCode == RESULT_OK
                  &amp;&amp; null != data) {
              Uri selectedImage = data.getData();
              String[] filePathColumn = { MediaStore.Images.Media.DATA };
  
              Cursor cursor = getContentResolver().query(selectedImage,
                      filePathColumn, null, null, null);
              cursor.moveToFirst();
  
              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
              String picturePath = cursor.getString(columnIndex);
              cursor.close();
  
              decodeFile(picturePath);
  
          }
      }
  
      class ImageUploadTask extends AsyncTask&lt;Void, Void, String&gt; {
          // private String webAddressToPost = "http://your-website-here.com";
  
          // private ProgressDialog dialog;
          private ProgressDialog dialog = new ProgressDialog(
                  SendPostActivity.this);
  
          @Override
          protected void onPreExecute() {
              dialog.setMessage("Uploading...");
              dialog.show();
          }
  
          @Override
          protected String doInBackground(Void... params) {
              try {
                  HttpClient httpClient = new DefaultHttpClient();
                  HttpContext localContext = new BasicHttpContext();
                  HttpPost httpPost = new HttpPost(Constant.serverUrl
                          + "PostComment");
  
                  MultipartEntity entity = new MultipartEntity(
                          HttpMultipartMode.BROWSER_COMPATIBLE);
  
                  ByteArrayOutputStream bos = new ByteArrayOutputStream();
                  bitmap.compress(CompressFormat.JPEG, 100, bos);
                  byte[] data = bos.toByteArray();
                  String file = Base64.encodeToString(data, Base64.DEFAULT);
                  entity.addPart("file", new StringBody(file));
                  entity.addPart(
                          "user_id",
                          new StringBody(Utility.getSharedPreferences(appContext,
                                  Constant.USER_ID)));
                  entity.addPart(
                          "msg_id",
                          new StringBody(Utility.getSharedPreferences(appContext,
                                  Constant.MESSAGE_ID)));
                  entity.addPart("type", new StringBody("image"));
  
                  httpPost.setEntity(entity);
                  HttpResponse response = httpClient.execute(httpPost,
                          localContext);
                  BufferedReader reader = new BufferedReader(
                          new InputStreamReader(
                                  response.getEntity().getContent(), "UTF-8"));
  
                  String sResponse = reader.readLine();
                  if (response != null) {
                      finalImagePath = sResponse;
                  }
                  return sResponse;
              } catch (Exception e) {
                  // something went wrong. connection with the server error
                  e.printStackTrace();
              }
              return null;
          }
  
          @Override
          protected void onPostExecute(String result) {
              dialog.dismiss();
              Toast.makeText(getApplicationContext(), "file uploaded",
                      Toast.LENGTH_LONG).show();
              System.out
                      .println("file is uploaded ////////////" + finalImagePath);
          }
  
       } // asyntask class ends 
  
  
  } // final class ends 
  </code></pre>
  
  <p>Here is my server api method: </p>
  
  <pre><code>function PostComment()
  {
    $obj = new funcs_code();
    $obj-&gt;connection();
    $output = "";  
    $uid = mysql_real_escape_string($_REQUEST['user_id']);
    $mid = mysql_real_escape_string($_REQUEST['msg_id']);
    $comm = "";
    $type = "text";
    if(isset($_REQUEST['type']))
    {
      $type = mysql_real_escape_string($_REQUEST['type']);
    }
    if(isset($_REQUEST['comment']))
    {
      $comm = mysql_real_escape_string($_REQUEST['comment']);
    }
    $sql = "SELECT * FROM `users` WHERE user_id = '$uid'";
    $res = mysql_query($sql);
    if(mysql_num_rows($res)==1)
    {
      $row = mysql_fetch_assoc($res);
      $sql1 = "SELECT * FROM `messages` WHERE msg_id = '$mid'";
      $res1 = mysql_query($sql1);
      if(mysql_num_rows($res1)==1)
      { 
        $row1 = mysql_fetch_assoc($res1);
        if($row['group_id'] == $row1['groupId'])
        {
            $status = 1; // 1 for comment
            $fileName = "";
  
            if(isset($_FILES['file']) &amp;&amp; is_array($_FILES['file']))
            {
              $allowedExts = array("jpeg", "jpg", "mp3", "mp4", "3gp");
              $temp = explode(".", $_FILES["file"]["name"]);
              $extension = end($temp);
  
              //
              //Check File Extension &amp; Size UPTO 5 MB
              //
  
              if (( $_FILES["file"]["type"] == "image/jpg"  || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "audio/mpeg"
              || $_FILES["file"]["type"] == "video/3gpp" || $_FILES["fiile"]["type"] == "video/mp4" ) &amp;&amp; $_FILES["file"]["size"] &lt; 5242880 &amp;&amp; in_array($extension, $allowedExts))
              {
                if ($_FILES["file"]["error"] &gt; 0)
                {
                  //echo "Return Code: " . $_FILES["file"]["error"] . "&lt;br&gt;";
                  $output = array('status' =&gt; 'error','message' =&gt; $_FILES["file"]["error"]);
                  header('content-type: application/json');
                  echo json_encode($output);
                  exit;
                }
                else
                {                
                    $fileName = time().".$extension";
                    move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/". $fileName);
                    $fileName = '/uploads/'.$fileName; 
                }
              }
              else
              {
                 $output = array('status' =&gt; 'error','message' =&gt; "Invalid_File");
                 header('content-type: application/json');
                 echo json_encode($output);
                 exit;
              }
  
              if($fileName != '' &amp;&amp; $type != 'text')
              {
                  $comm = $fileName;
              }
  
            }
  
            //
            //Below Condition Used to check, If uploading any media and File not Uploaded
            //
            if($type != 'text' &amp;&amp; $fileName == ""){         
                 $output = array('status' =&gt; 'error','message' =&gt; "Please, Specify valid Parameter for file");
                 header('content-type: application/json');
                 echo json_encode($output);
                 exit;
            }
  
            //
            //In Any Case Comment can not be left blank
            //
            if($comm != "")
            {
                $sq = "INSERT INTO `user_comment`(`user_id`,`msg_id`,`type`,`comment`,`status`) VALUES('$uid','$mid','$type','$comm','$status')";
  
                if(mysql_query($sq))
                  $output = array('status' =&gt; 'success','message' =&gt; "Comment_Success");
                else
                  $output = array('status' =&gt; 'error','message' =&gt; "Comment_Fail");
  
            }else{
                 $output = array('status' =&gt; 'error','message' =&gt; "Comment Can not be blank");
                 header('content-type: application/json');
                 echo json_encode($output);
                 exit;
            }
            ///////////////////////////  
  
        }// group
        else
        {
          //$output = 'user_group not match';
          $output = array('status' =&gt; 'error','message' =&gt; "User_group_Not_match");
        }
      }
      else
      {
        //$output = 'invalid msg_id';
        $output = array('status' =&gt; 'error','message' =&gt; "Invalid_Msg_id");
      }
    }
    else
    {
      //$output = "invalid user_id";
      $output = array('status' =&gt; 'error','message' =&gt; "Invalid_User");
    }
  header('content-type: application/json');
  echo json_encode($output);
  }
  </code></pre>