我想编写 Java 应用程序,它将使用 PHP 将文件上传到 Apache 服务器。Java 代码使用 Jakarta HttpClient 库版本 4.0 beta2:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
public class PostFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:9002/upload.php");
File file = new File("c:/TRASH/zaba_1.jpg");
FileEntity reqEntity = new FileEntity(file, "binary/octet-stream");
httppost.setEntity(reqEntity);
reqEntity.setContentType("binary/octet-stream");
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();
}
}
PHP 文件upload.php
非常简单:
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES);
}
?>
阅读响应我得到以下结果:
executing request POST http://localhost:9002/upload.php HTTP/1.1
HTTP/1.1 200 正常 可能的文件上传攻击:文件名''。 大批 ( )
所以请求成功,我能够与服务器通信,但是 PHP 没有注意到文件 - 方法is_uploaded_file
返回false
并且$_FILES
变量为空。我不知道为什么会发生这种情况。我跟踪了 HTTP 响应和请求,它们看起来不错:
请求是:
POST /upload.php HTTP/1.1 内容长度:13091 内容类型:二进制/八位字节流 主机:本地主机:9002 连接:保持活动 用户代理:Apache-HttpClient/4.0-beta2 (java 1.5) 期望:100-继续 ˙Ř˙ŕ.....二进制文件的其余部分...
和回应:
HTTP/1.1 100 继续 HTTP/1.1 200 正常 日期:格林威治标准时间 2009 年 7 月 1 日星期三 06:51:57 服务器:Apache/2.2.8 (Win32) DAV/2 mod_ssl/2.2.8 OpenSSL/0.9.8g mod_autoindex_color PHP/5.2.5 mod_jk/1.2.26 X-Powered-By: PHP/5.2.5 内容长度:51 保活:超时=5,最大值=100 连接:保持活动 内容类型:文本/html 可能的文件上传攻击:filename ''.Array ( )
我在带有 xampp 的本地 windows xp 和远程 Linux 服务器上都对此进行了测试。我也尝试使用以前版本的 HttpClient - 3.1 版 - 结果更加不清楚,is_uploaded_file
返回了false
,但是$_FILES
数组中填充了正确的数据。