2

After bodging together code from reading this: Using java.net.URLConnection to fire and handle HTTP requests

The upload appears to work, and will return 200 to the android device. Also the PHP FILE isn't in error. However while it has the correct name and other info, the file size is 0.

Android (Java) Code Private String httpPost(Uri fileUri) {
     String url = "http://MyUrl/testPhone.php";
    String result;
    File file = new File(fileUri.getPath());
    try {

        String charset = "UTF-8";
        String param = "value";
        File binaryFile = new File(fileUri.getPath());
        String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
        String CRLF = "\r\n"; // Line separator required by multipart/form-data.

        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (
                OutputStream output = connection.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        ) {
            // Send normal param.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
            writer.append(CRLF).append(param).append(CRLF).flush();



          //  output.flush(); // Important before continuing with writer!
          //  writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

            // Send binary file.
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" +binaryFile.getName() + "\"").append(CRLF);
            writer.append("Content-Type: application/pdf").append(CRLF);
            writer.append("Content-Transfer-Encoding: binary").append(CRLF);
            writer.append(CRLF).flush();

            output.flush(); // Important before continuing with writer!
            writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

            // End of multipart/form-data.
            writer.append("--" + boundary + "--").append(CRLF).flush();
        }

        int responseCode = ((HttpURLConnection) connection).getResponseCode();

        System.out.println(responseCode); // Should be 200
        result = "http://MyUrl/testPhone.php?uuid=" + responseCode+ "Test"+binaryFile.length();

    }
     catch (Exception e) {
        result = "http://MyUrl/testPhone.php" + "?uuid=" + e;
     }
    return result;
}

PHP Code:

echo $_GET["uuid"];

$file = $_FILES["binaryFile"]["tmp_name"];


if (file_exists($file))
{

foreach($_FILES['binaryFile'] as $key => $val){
    error_log(date('j/n/o H:i:s')." ". $key ." = ".$val);
}
error_log (disk_free_space("/"));

   // $result .= $thisEventDB->execSql('insert into Files values (0, ?, ?,    NOW(), ?, ?, ?, 0)', array(6,$file, $fileData, $fileData, md5_file($file)));


}

Error Log:

[Wed Aug 26 14:41:13 2015] [error] 26/8/2015 14:41:13 name => Getting Started.pdf [Wed Aug 26 14:41:13 2015] [error] 26/8/2015 14:41:13 type => application/pdf [Wed Aug 26 14:41:13 2015] [error] 26/8/2015 14:41:13 tmp_name => /usr/local/var/php/php7P1M4j [Wed Aug 26 14:41:13 2015] [error] 26/8/2015 14:41:13 error => 0 [Wed Aug 26 14:41:13 2015] [error] 26/8/2015 14:41:13 size => 0 [Wed Aug 26 14:41:13 2015] [error] 7182110720

binaryFIle.Length Returns 131990 in the android code, so appears to have the correct file path.

I am unsure where to go from here.

Community
  • 1
  • 1
ID 10 T
  • 45
  • 4

1 Answers1

1

I don't see where you are writing the file to the request stream?

writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();

output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush();

How are you writing the actual file content?

One of the methods proposed here may work for you:

Easy way to write contents of a Java InputStream to an OutputStream

Community
  • 1
  • 1
ryachza
  • 4,195
  • 16
  • 28
  • Yeah I felt like I was missing that part... I just couldn't see where it should go. Will read this / test it out and get back to you. Cheers! – ID 10 T Aug 26 '15 at 15:23
  • @ID10T I don't know for sure because I've never submitted a multi-part form at such a low level, but my intuition is you need to write the contents of the file to `output` between the two `writer.append(CRLF)` calls. My hope would be that the output stream would just handle everything properly from there. – ryachza Aug 26 '15 at 15:26
  • @ID10T Do you have any higher-level options available? I'm more familiar with this type of structure: http://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java i.e. creating "parts" and "appending" them to a request that handles all the boundary and writing stuff for you. – ryachza Aug 26 '15 at 15:29
  • I'm not 100% sure what you mean, but I believe I do have higher-level options available. I'm on kitkat 4.4.2 – ID 10 T Aug 26 '15 at 15:39
  • I can't import the class mentioned here 'MultipartEntityBuilder', It does not appear to found in androidStudio – ID 10 T Aug 26 '15 at 15:42
  • @ID10T I'm sorry I can't be much help because I've barely done any Android development. I have used libraries that facilitate these types of things in Java, but don't know what's available for Android. Do you have the ability to add libraries? I think the one referenced is this: http://hc.apache.org/ – ryachza Aug 26 '15 at 15:46