我需要一种上传文件并将其 POST 到 php 页面的方法...
我的 php 页面是:
<?php
$maxsize = 10485760;
$array_estensioni_ammesse=array('.tmp');
$uploaddir = 'uploads/';
if (is_uploaded_file($_FILES['file']['tmp_name']))
{
if($_FILES['file']['size'] <= $maxsize)
{
$estensione = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], "."), strlen($_FILES['file']['name'])-strrpos($_FILES['file']['name'], ".")));
if(!in_array($estensione, $array_estensioni_ammesse))
{
echo "File is not valid!\n";
}
else
{
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
echo "File ". $_FILES['file']['name'] ." uploaded successfully.\n";
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile))
{
echo "File is valid, and was successfully moved.\n";
}
else
print_r($_FILES);
}
}
else
echo "File is not valid!\n";
}
else
{
echo "Upload Failed!!!";
print_r($_FILES);
}
?>
我在我的桌面应用程序中使用这个java代码:
HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestMethod("POST");
OutputStream os = httpUrlConnection.getOutputStream();
Thread.sleep(1000);
BufferedInputStream fis = new BufferedInputStream(new FileInputStream("tmpfile.tmp"));
long totalByte = fis.available();
long byteTrasferred = 0;
for (int i = 0; i < totalByte; i++) {
os.write(fis.read());
byteTrasferred = i + 1;
}
os.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
httpUrlConnection.getInputStream()));
String s = null;
while ((s = in.readLine()) != null) {
System.out.println(s);
}
in.close();
fis.close();
但我总是收到“上传失败!!!”信息。
尽管该线程很旧,但可能仍然有人在寻找更简单的方法来解决这个问题(就像我:))
经过一番研究,我找到了一种在不更改原始发布者的 Java 代码的情况下上传文件的方法。
您只需使用以下 PHP 代码:
<?php
$filename="abc.xyz";
$fileData=file_get_contents('php://input');
$fhandle=fopen($filename, 'wb');
fwrite($fhandle, $fileData);
fclose($fhandle);
echo("Done uploading");
?>
这段代码只是获取 java 应用程序发送的原始数据并将其写入文件。
然而,有一个问题:您没有获得原始文件名,因此您必须以其他方式传输它。
我通过使用 GET 参数解决了这个问题,这需要对 Java 代码进行一些更改:
HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection();
更改为
HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php?filename=abc.def").openConnection();
在你的 PHP 脚本中你改变这一行
$filename="abc.xyz";
to
$filename=$_GET['filename'];
该解决方案不使用任何外部库,在我看来比其他一些发布的解决方案简单得多......
希望我能帮助任何人:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)