0

I am currently using hosting24.com for php file upload implementation and going to upload mp4 files. The html file for testing , it workds. When it comes to the execution by Android deivces , it fails and shows the $name = $_FILES["uploaded_file"] is null. Would you please tell me is there any other factors preventing us from successful upload ?

The below is my code

public String uploadFIle(File file){
        String result = "";

        HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String fileName =  file.getName();
        int bytesRead, bytesAvailable, bufferSize;
        int serverResponseCode = 0;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 

        FileInputStream fileInputStream;
        try {
            fileInputStream = new FileInputStream(file);
            URL url = new URL("http://www.gallicalab.com/upload.php");

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

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

            dos.writeBytes(twoHyphens + boundary + lineEnd); 
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_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();
            InputStream is = conn.getInputStream();

            if(serverResponseCode==200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(    is, "utf-8"), 8192);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                result =   sb.toString();  
            }



        //  result = serverResponseMessage;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return result;
    }

Server side

<?php
error_reporting(E_ALL);

    $target_path  = "target/";
  //  $target_path = $target_path . basename( $_FILES['file']['name']);
    $name = $_FILES["uploaded_file"]["name"];
  //  echo $name."<br>";
    $ext = end(explode(".", $name));
    //    echo $ext."<br>";
    $randname = random_string(30);
   // echo $randname."<br>";
    $fname = $randname . "." .$ext;
    //echo $fname."<br>";
    $target_path = $target_path .$fname;
   // echo $target_path."<br>";
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
        //echo "The file ".  basename( $_FILES['file']['name'])." has been uploaded";
        //echo random_string(50);



        // $arr = array ('data'=>'http://gallicalab.com/target/'.$_FILES['file']['name']);
        $arr = array ('data'=>'http://gallicalab.com/target/'.$fname);

        echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
    } 
    else {
        echo "There was an error uploading the file, please try again!";
    }



    function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
    }

?>
1

1 Answer 1

1

Could you log what you are actually receiving at the server side to a file? Android app might not be making the request correctly.

Try this:

<?php
error_reporting(E_ALL);

$h = fopen('upload.log', 'w');
fwrite($h, print_r($_POST, true) ."\r\n---\r\n");
fwrite($h, print_r($_FILES, true));
fclose($h);

// rest of your code

Then inspect the upload.log file and see what happened with your request from device.


P.S. Try this alternate upload code for android:

private void uploadFile(String filePath, String fileName) {
  InputStream inputStream;
  try {
    inputStream = new FileInputStream(new File(filePath));
    byte[] data;
    try {
      data = IOUtils.toByteArray(inputStream);

      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost("http://www.gallicalab.com/upload.php");

      InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
      MultipartEntity multipartEntity = new MultipartEntity();
      multipartEntity.addPart("file", inputStreamBody);
      httpPost.setEntity(multipartEntity);

      HttpResponse httpResponse = httpClient.execute(httpPost);

      // Handle response back from script.
      if(httpResponse != null) {

      } else { // Error, no response.

      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  } catch (FileNotFoundException e1) {
    e1.printStackTrace();
  }
}

At server side:

$objFile = & $_FILES["file"];
$strPath = basename( $objFile["name"] );

if( move_uploaded_file( $objFile["tmp_name"], $strPath ) ) {
    print "The file " .  $strPath . " has been uploaded.";
} else {
    print "There was an error uploading the file, please try again!";
}

Source: http://www.codepuppet.com/2013/03/26/android-uploading-a-file-to-a-php-server/

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

3 Comments

Array ( ) --- Array ( ) It is still empty even using your method
and I am using hosting24.com
I have also posted this question .... stackoverflow.com/questions/21162665/…

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.