I'm trying to upload & rename a file from a java program.
My java upload method:
public void bestandUploaden(String oudeUrl, String nieuweNaam) throws ParseException, IOException {
System.out.println("oude url: " + oudeUrl);
System.out.println("nieuwe naam: " + nieuweNaam);
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("**Website url**/upload_file.php");
File file = new File(oudeUrl);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("file", new FileBody(file));
mpEntity.addPart("uniekeNaam", new StringBody(nieuweNaam));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
My php code:
<?php
echo "Nieuwe bestandsnaam :" . $_FILES["uniekeNaam"];
$disallowedExts = array("exe");
$extension = end(explode(".", $_FILES["file"]["name"]));
if (!in_array($extension, $disallowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("documenten/" . $_FILES["uniekeNaam"]))
{
echo $_FILES["uniekeNaam"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"documenten/" . $_FILES["uniekeNaam"]);
echo "Stored in: " . "documenten/" . $_FILES["uniekeNaam"];
}
}
}
else
{
echo "Invalid file";
}
?>
My java console output:
oude url: D:\Dropbox\Documents\youtube.txt
nieuwe naam: Een_textbestand.txt
executing request POST **Website url**/upload_file.php HTTP/1.1
HTTP/1.1 200 OK
Nieuwe bestandsnaam :Upload: youtube.txt<br>Type: application/octet-stream<br>Size: 1.8095703125 kB<br>Temp file: /tmp/phpp9igba<br> already exists.
As you can see the 'uniekeNaam' isn't transfered from my java to my php part. It's empty. I don't have any php knowledge and tried different things but nothing seems to work. I just want to be able to browse to a file in my java program and upload that file to a webserver and rename it. If I leave the renaming out it works so I think I just need to figure out how to transfer the 'uniekeNaam' from java to php.
If i do:
print_r($_FILES);
I get:
Array (
[file] => Array (
[name] => motoplus.pdf
[type] => application/octet-stream
[tmp_name] => /tmp/php0V4SCS
[error] => 0 [size] => 1010671
)
)
In your php file just type:
print_r($_FILES);
to see whether you are receiving that "uniekeNaam" variable or not.