title: file upload to php server from android not working
body: <p>I am trying to upload a mp3 file from my android device(2.3.3) but failing. I have seen lot of similar queries here but could not find any solution for my problem. I am not very good in php</p>
  
  <p>Following is my implementation in a service which I am starting from an Activity</p>
  
  <pre><code>import java.io.DataInputStream;
  import java.io.DataOutputStream;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.IOException;
  import java.net.HttpURLConnection;
  import java.net.URL;
  
  import android.app.IntentService;
  import android.content.Intent;
  import android.content.SharedPreferences;
  import android.util.Log;
  
  public class SendFileService extends IntentService {
  private boolean mFileSent = false;
  
  public SendFileService() {
      super("SendFileService");
  
  }
  
  @Override
  protected void onHandleIntent(Intent arg0)
  {
      if(arg0 != null)
      {
          final String path = arg0.getStringExtra("path");
          if(path != null &amp; path.length() &gt; 0)
          {
              Thread t = new Thread()
              {
                  public void run()
                  {
                      try
                      {
                          sendFilewithHTTP(path);
                          while(mFileSent == false)
                          {
                              Thread.sleep(1000 * 60 * 10);// 10 minutes
                              sendFilewithHTTP(path);
                          }   
  
                      }
                      catch (InterruptedException e)
                      {
                          e.printStackTrace();
                      }
                  }
              };
              t.start();
          }
      }
  }
  
  @Override
  public void onDestroy()
  {
      mFileSent = true;
      super.onDestroy();
  }
  
  private void sendFilewithHTTP(String filePath)
  {
      //Set a global flag to check
      SharedPreferences settings = getSharedPreferences("INFO", MODE_PRIVATE);
  
      HttpURLConnection connection = null;
      DataOutputStream outputStream = null;
      DataInputStream inStream = null;
      if(filePath == null || filePath.length() &lt;3)
      {
          mFileSent = true;
          return;
      }
  
      String pathToOurFile = filePath;
      String urlServer = "https://www.xxxx.xx/xxx/xxxxxxxx/xxxxxx.php?lang=en&amp;val=" + settings.getString("val", getString(R.string.VAL));
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary =  "*****";
  
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1*1024*1024;
  
      FileInputStream fileInputStream = null;
  
      try
      {
          fileInputStream = new FileInputStream(new File(pathToOurFile) );
  
          URL url = new URL(urlServer);
          connection = (HttpURLConnection) url.openConnection();
          Log.i("Connecting to: ", urlServer);
  
          // Allow Inputs &amp; Outputs
          connection.setDoInput(true);
          connection.setDoOutput(true);
          connection.setUseCaches(false);
  
          // Enable POST method
          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=\"" + pathToOurFile +"\"" + 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)
          int serverResponseCode = connection.getResponseCode();
          String serverResponseMessage = connection.getResponseMessage();
          Log.i("File sent to: " + filePath, "Code: " + serverResponseCode + " Message: " + serverResponseMessage);
  
          mFileSent = true;
          fileInputStream.close();
          outputStream.flush();
          outputStream.close();
          //connection.disconnect();
          }
          catch (Exception ex)
          {
              Log.i("File sent status ", "Connection Failed");
              ex.printStackTrace();
              try
              {
                  if(fileInputStream != null)
                      fileInputStream.close();
                  if(connection != null)
                      connection.disconnect();
                  if(outputStream != null)
                  {
                      outputStream.flush();
                      outputStream.close();
                  }
  
              }
              catch(Exception e)
              {
  
              }
          }
  
          try {
              inStream = new DataInputStream ( connection.getInputStream() );
              String str;
  
              while (( str = inStream.readLine()) != null)
              {
                  Log.d("Server response: ", str);
              }
              inStream.close();
  
        }
        catch (IOException ioex){
  
        }
  
        if(connection != null)
          connection.disconnect();
  
  
  }
  
  }
  </code></pre>
  
  <p>The following permissions are added in the manifest</p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;
  &lt;uses-permission android:name="android.permission.INTERNET"&gt;&lt;/uses-permission&gt;
  </code></pre>
  
  <p>This is my PHP script running at the server:
          
  
  <pre><code>    //check if we have a language and val
      $lang=$_GET['lang'];
      $val=$_GET['val'];
  
  if ( (!isset($val)) || (!isset($lang)) ) die('false');
  if ( ($val="") || ($lang="") ) die('false');
  
  
  //get the file
  $fn="data/mydata-".uniqid()."-". date("YmdHis") . ".mp3";
  
  if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $fn)) 
  {
      die('false: There was no file in the post request');
  }
  
  
  //check if it's am MP3
  $mp3_mimes = array('audio/mpeg3', 'audio/x-mpeg-3', 'audio/mpeg'); 
  if (!in_array(mime_content_type($fn), $mp3_mimes)) {
    echo "false: Content type not MP3";
      unlink($fn);        
  
  } else 
  {
  
      //now let's check the file size:
      if (filesize($fn)&lt;(1024*1024*10))
      {
          //Do Something      
      }
      else echo "false: File size too big";   
  } 
  
  ?&gt;
  </code></pre>
  
  <p>I am able to connect to the server &amp; the HTTP server is sending message code =200 and message=OK. However, the php script is not getting any files. The function move_uploaded_file() is returning false &amp; hence I am getting value false in my device. I have tried with variety of file sizes but failing.</p>
  
  <p>However, I was able to upload a mp3 file to the same php script from my desktop browser.
  I believe this rules out any possibility of ini file mistakes or security settings issues.</p>
  
  <p>Please help me find the solution.</p>
  
  <p>Thanks in advance</p>