Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've already searched a lot and have not found a specific solution for my problem.

First of all, I'm communicating with my Android app between a php web service using json. My objective is to discover why the variable $uploaded_file is returning blank but the file is uploaded normally to the server, with the correct name and extension. If the file appears at the server, how could the $_FILES array be blank?

When I upload the file through the html form upfile.html, the $_FILES array is not empty. So, I guess my problem is with some property that the java sends to the php, which one could it be? Please, take a look at the java method fileUpload below.

upfile.html

<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

upload.php

$uploaded_file = $_FILES["file"]["name"];

if ($_FILES["file"]["error"] > 0)
{
    $response["success_image"] = 0;
    $response["message_update_image"] = "Error while trying to update image";
    die(json_encode($response));
}
    else
    {

        //echo "Name: " . $_FILES["file"]["name"] . "<br>";
        if (file_exists("upload/" . $uploaded_file))
        {
            $response["success_image"] = 0;
            $response["message_update_image"] = "Image already exists";
            die(json_encode($response));
        }
        else
        {
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "upload/" . $uploaded_file);
            $query = "UPDATE user SET image = :image WHERE id = :user";
            $query_params = array(
                ':user' => $_POST['user'],
                ':image' => $uploaded_file
            );

            try {
                $stmt   = $db->prepare($query);
                $result = $stmt->execute($query_params);
            }
            catch (PDOException $ex) {

                $response["success_image"] = 0;
                $response["message_update_image"] = "Unable to upload image";
                die(json_encode($response));
            }

        $response["success_image"] = 1;
        //$response["message_update_image"] = "Image uploaded";
        $response["message_update_image"] = $uploaded_image;
        echo json_encode($response);
      }
 }

?>

the fileUpload method that sends the file to the php server.

public int fileUpload(String sourceFileUri) {
  String fileName = sourceFileUri;

        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()) {

             Log.e("uploadFile", "Source File not exist :" +sourceFileUri);

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

             return 0;

        }
        else
        {
             try { 

                   // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(UPLOAD_URL);

                 // 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("file", fileName); 

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

                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
                 dos.writeBytes("Content-Disposition: form-data; name=file; filename="
                                           + fileName + "" + 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("uploadFile", "HTTP Response is : "
                         + serverResponseMessage + ": " + serverResponseCode);

                 if(serverResponseCode == 200){

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



                              Toast.makeText(EditProfile.this, "File Upload Complete.", 
                                           Toast.LENGTH_SHORT).show();
                          }
                      });                
                 }    

                 //close the streams //
                 fileInputStream.close();
                 dos.flush();
                 dos.close();

            } catch (MalformedURLException ex) {


                ex.printStackTrace();

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

                        Toast.makeText(EditProfile.this, "MalformedURLException", 
                                                            Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
            } catch (Exception e) {

                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(EditProfile.this, "Got Exception : see logcat ", 
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "
                                                 + e.getMessage(), e);  
            }
            return serverResponseCode; 

         } // End else block 
       } 
share|improve this question
add comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.