Upload a FIle to PHP Script with Android
<p>I want to Upload a FIle to a PHP script. The Upload seems to work fine, it is sending Data out. But the PHP Script everytime just tells me, that  $_FILES is empty... I don't know what i did wrong.. Any Idea whats wrong with my code?</p>

<pre><code>import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Settings.Secure;
import android.util.Log;

public class Upload extends AsyncTask&lt;Object, Integer, String&gt; {
    URL connectURL;
    String responseString;
    String usernameString;
    Context con;
    String iFileName;
    byte[] dataToServer;
    FileInputStream fileInputStream = null;

    void Sending() {

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag = "Info";
        try {
            Log.e(Tag, "Starting Http File Sending to URL");

            // Open a HTTP connection to the URL
            HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();

            // Allow Inputs
            conn.setDoInput(true);

            // Allow Outputs
            conn.setDoOutput(true);

            // Don't use a cached copy.
            conn.setUseCaches(false);

            // Use a post method.
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

            Log.d("Info", iFileName);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            Log.e(Tag, "Headers are written");

            // create a buffer of maximum size
            int bytesAvailable = fileInputStream.available();

            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[] buffer = new byte[bufferSize];

            // read file and write it into form...
            int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead &gt; 0) {
                Log.e(Tag, "sending...");
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            fileInputStream.close();

            dos.flush();

            Log.e(Tag, "File Sent, Response: " + String.valueOf(conn.getResponseCode()));

            InputStream is = conn.getInputStream();

            // retrieve the response from server
            int ch;

            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            String s = b.toString();
            Log.i("Response", s);
            dos.close();

            String aidString = Secure.getString(con.getContentResolver(), Secure.ANDROID_ID);
            //new BackgroundPost(new OnTaskComplete() {}).execute(usernameString, s, "0", "0", aidString, "");
        } catch (MalformedURLException ex) {
            Log.e(Tag, "URL error: " + ex.getMessage(), ex);
        }

        catch (IOException ioe) {
            Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
        }
    }

    public void run() {
        // TODO Auto-generated method stub
    }

    @Override
    protected String doInBackground(Object... params) {
        try {
            connectURL = new URL(conf.d + "upload.php");
            usernameString = String.valueOf(params[0]);
            con = (Context)params[1];
            Random random = new Random(); 
            String u = (String) params[2];
            Log.d("Info","u: " + u);
            iFileName = random.nextInt() +  "." + u.substring(u.lastIndexOf(".")+1);
            Log.d("Info","filename: " + iFileName);
            fileInputStream = new FileInputStream(u);
            Sending();

        } catch (Exception ex) {
            ex.printStackTrace();
            Log.i("HttpFileUpload", "URL Malformatted");
        }
        // TODO Auto-generated method stub
        return null;
    }
}
</code></pre>

<p>And the PHP FIle:</p>

<pre><code>  &lt;?php
  $target_path = "uploads/";

  print_r($_FILES);

  $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>
