Upload and POST file to PHP page with Java

Even though the thread is very old, there may still be someone around looking for a more easy way to solve this problem (like me :))

After some research I found a way to uplaod a file without changing the original poster’s Java-Code.
You just have to use the following PHP-code:

<?php
  $filename="abc.xyz";
  $fileData=file_get_contents('php://input');
  $fhandle=fopen($filename, 'wb');
  fwrite($fhandle, $fileData);
  fclose($fhandle);
  echo("Done uploading");
?>

This code is just fetching the raw data sent by the java-application and writing it into a file.
There is, however one problem: You dont get the original filename, so you have to transmit it somehow else.

I solved this problem by using a GET-Parameter, which makes a little change in the Java-code necessary:

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection();

changes to

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php?filename=abc.def").openConnection();

In your PHP-script you change the line

$filename="abc.xyz";

to

$filename=$_GET['filename'];

This solution doesn’t use any external librarys and seems to me much more simple than some of the other posted ones…

Hope I could help anyone:)

Leave a Comment