2

I'm trying to upload a image from Android App to a server with a PHP Script. The HTTP Response returns STATUS OK: 200, but the $_FILES["upfile"]["name"] returns empty. I`ve checked my folders permissions and aready is 777.

My .java class

  /********************UPLOAD DATA*************************************/
class UploadImg extends AsyncTask<Void, Void, Void>{

    NetworkInfo net;

    Messaging uActivity;

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String folderPath;
    String arrayOfFiles[];
    File root;
    File allFiles;

    String urlServer = "http://bmcpublicidade.com.br/chat/upload.php";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 10*1024*1024;

    URL url;

     ProgressDialog pDialog = new ProgressDialog(Messaging.this);



    @Override
    protected void onPreExecute() {


        Log.d(" UploadImg","onPreRequest");

            pDialog.setMessage("Uploading GPS Data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();


    }

    @Override
    protected Void doInBackground(Void... params) {

         Log.d(" UploadData","doInBackground");

         String fileName = ""+selectedPath;
         HttpURLConnection conn = null;
         DataOutputStream dos = null;
         BufferedReader inStream = null;
         String lineEnd = "rn";
         String twoHyphens = "--";
         String boundary =  "*****";
         int bytesRead, bytesAvailable, bufferSize;
         byte[] buffer;
         int maxBufferSize = 10*1024*1024;
         String responseFromServer = "";
         String urlString = "http://bmcpublicidade.com.br/chat/upload.php";
         try
         {
          //------------------ CLIENT REQUEST
         FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
          // open a URL connection to the Servlet
          URL url = new URL(urlString);
          // Open a HTTP connection to the URL
          conn = (HttpURLConnection) url.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("enctype", "multipart/form-data");
          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
          conn.setRequestProperty("upfile", fileName); 
          dos = new DataOutputStream( conn.getOutputStream() );
          dos.writeBytes(twoHyphens + boundary + lineEnd);
          dos.writeBytes("Content-Disposition: form-data; name=\"upfile\"; filename='"+ selectedPath +"'" + 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 > 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("upfile", "HTTP Response is : "
                  + serverResponseMessage + ": " + serverResponseCode);

          if(serverResponseCode == 200){

              runOnUiThread(new Runnable() {
                   public void run() {

                       String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                     +" http://**********/media/uploads/";

                       messageText.setText(msg);
                       Toast.makeText(Messaging.this, "File Upload Complete.", 
                                    Toast.LENGTH_SHORT).show();
                   }
               });                
          }    

          // close streams
          Log.e("Debug","gravando arquivo: " + fileName);
          fileInputStream.close();
          dos.flush();
          dos.close();
         }
         catch (MalformedURLException ex)
         {
              Log.e("Debug", "erro: " + ex.getMessage(), ex);
         }
         catch (IOException ioe)
         {
              Log.e("Debug", "erro: " + ioe.getMessage(), ioe);
         }
         //------------------ read the SERVER RESPONSE
         try {
               inStream = new BufferedReader ( new InputStreamReader(conn.getInputStream()) );
               String str;

               while (( str = inStream.readLine()) != null)
               {
                    Log.e("Debug","Servidor diz:  "+str);
               }
               inStream.close();

         }
         catch (IOException ioex){
              Log.e("Debug", "erro: " + ioex.getMessage(), ioex);
         }


    return null;
    }

    @Override
    protected void onPostExecute(Void result) {

         Log.d(" UploadMSG","onPost");

        pDialog.dismiss();

        messageText.setText("Uploaded");
    }
}
/********************END OF UPLOAD*************************************/

and here is my php file

// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "/uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['upfile']['name']);

if( $_FILES['upfile'] )
{
    if(move_uploaded_file($_FILES['upfile']['tmp_name'], $target_path)) {

        // $qry = "UPDATE users set image=".$target_path." where username='$username'";
        // $db->query($qry);

        echo "O arquivo ".  basename( $_FILES['upfile']['name']).
        " está sendo enviado";
    } else{
        echo "Ocorreu um erro ao realizar envio de arquivo, por favor tente novamente!\n";
        echo "Nome do arquivo: " .  basename( $_FILES['upfile']['name'])."\n";
        echo "target_path: " .$target_path;
    }
}else
{
    echo "Nenhum arquivo careregado!"; 



    /*** ever enters here!!! ***/
}

Can you help me?

thanks !!!

3
  • 1
    if you'd bothered doing var_dump($_FILES), you'd see that your Java code is setting upfile as your file's uploadname, but your PHP code is looking for uploadedfile. Commented Aug 18, 2014 at 17:58
  • I`ve copied the wrong script, edited! Error persist witha "right" script Commented Aug 18, 2014 at 18:16
  • stuck in same issue can anyone help?stackoverflow.com/questions/29299839/… Commented Apr 2, 2015 at 5:12

3 Answers 3

1

I've just encountered the same issue. POSTing a file succeeds with a 200 response, but _FILES is empty. I fixed the issue by specifying the Content-Length header. E.g.:

conn.setRequestProperty("Content-Length", Integer.toString(fileInputStream.available()));

Edit: So, when using this, the file appeared in _FILES but with an error code of 3. However, I also had a call to conn.setChunkedStreamingMode(1024);. Removing the Content-Length and the call to setChunkedStreamingMode worked for me, but I'm pretty sure that the empty _FILES is to do with the Content-Length field not being set correctly.

Sign up to request clarification or add additional context in comments.

Comments

1

Code looks fine but in your AsyncTask doInBackground Method, change String lineEnd = "rn"; To String lineEnd = "\r\n"; Should work. The backward slashes ensure r, n are not interpreted as letters but as special characters, r- return carriage, and n- new line.

1 Comment

0

I have the same problem. I described it here. In my case problem is only when I'm trying to send file with content type "multipart/form-data". And I didn't solve it, maybe it deals with php or server, but question is still without answer.

As temporary solution I changed request type to default post type (application/x-www-form-urlencoded) and transfered image as base64 string. Maybe it help.

1 Comment

I'll try to do the "trick" =). Thanks and good lucky with your problem too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.