title: upload image with username from android to server using multipart post
body: <p>i want to upload an image and the username from my android application to my server. i developped this code.
  in my database i find the image without username ( value 0).i think that i should use the asynctask but i have no idea how to make it. i want to use this method if it's possible.</p>
  
  <p>this is my code:</p>
  
  <pre><code>public int uploadFile(String sourceFileUri) {
  
      String fileName = sourceFileUri;
      String ref_name = "toto";
  
      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);
          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("image", fileName);
            conn.setRequestProperty("ref_name",ref_name);
  
              dos = new DataOutputStream(conn.getOutputStream());
              dos = new DataOutputStream(conn.getOutputStream());
  
              dos.writeBytes(twoHyphens + boundary + lineEnd);
              dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename="+ fileName + ";ref_name=" + ref_name+ ""+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 &gt; 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){
  
                  getActivity().runOnUiThread(new Runnable() {
                      public void run() {
  
                          Toast.makeText(getActivity(), "File Upload Complete.", Toast.LENGTH_SHORT).show();
                      }
                  });
              }
  
              //close the streams //
              fileInputStream.close();
              dos.flush();
              dos.close();
  
          } catch (MalformedURLException ex) {
  
              dialog.dismiss();
              ex.printStackTrace();
  
              getActivity().runOnUiThread(new Runnable() {
                  public void run() {
  
                      // Toast.makeText(New_annonce_act_step3.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });
  
              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
          } catch (Exception e) {
  
              dialog.dismiss();
              e.printStackTrace();
  
              getActivity().runOnUiThread(new Runnable() {
                  public void run() {
  
                      Toast.makeText(getActivity(), "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : "
                      + e.getMessage(), e);
          }
          dialog.dismiss();
          return serverResponseCode;
  
      } // End else block
  }
  
  public String getPath(Uri uri) {
      String[] projection = { MediaStore.Images.Media.DATA };
      Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
  
     // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA);
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  
      cursor.moveToFirst();
      return cursor.getString(column_index);
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>Server code:private function do_upload()
  {
      $type = explode('.', $_FILES["image"]["name"]);
      $type = strtolower($type[count($type)-1]);
  
      $img=uniqid(rand()).'.'.$type; 
                          $url = "./images/".$img;
  
  
      if(in_array($type, array("jpg", "jpeg", "gif", "png")))
          if(is_uploaded_file($_FILES["image"]["tmp_name"]))
              if(move_uploaded_file($_FILES["image"]["tmp_name"],$url))
  
                  return $img;
  
      return "";
  }
  </code></pre>
  
  <p>for this code: i don't know if i should post only the image or the image and the username. that why i make 2 codes.</p>
  
  <pre><code>    public function save_image_relation_post(){
      $ref_name = $_POST["ref_name"];
  
      $url = $this-&gt;do_upload();
      $this-&gt;Images_model-&gt;save_image($ref_name, $url);
  }
  </code></pre>
  
  <p>function with post image only:</p>
  
  <pre><code>public function save_image_test_post(){
   $url= $this-&gt;do_upload();
    $this-&gt;Images_model-&gt;save_image_test($url);
     }
  </code></pre>