通过php上传java文件
我正试图用java在我的php服务器上上传一个文件,但是每次我运行代码时,我的httprequest都会失败,我不知道原因是什么,首先我认为这可能是由multipartentity方法引起的,我之前把它的参数留空了,但现在在填充它之后,同样的问题仍然出现通过php上传java文件,java,php,Java,Php,我正试图用java在我的php服务器上上传一个文件,但是每次我运行代码时,我的httprequest都会失败,我不知道原因是什么,首先我认为这可能是由multipartentity方法引起的,我之前把它的参数留空了,但现在在填充它之后,同样的问题仍然出现 //this is my java code String path="E:\\upload.txt"; HttpClient hc=new DefaultHttpClient(); hc.getParams(
//this is my java code
String path="E:\\upload.txt";
HttpClient hc=new DefaultHttpClient();
hc.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost hp=new HttpPost("http://localhost/shoolPHP/uploadFile.php");
File f=new File(path);
MultipartEntity me=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cf=new FileBody(f);
me.addPart("userfile", cf);
hp.setEntity(me);
System.out.println("executing request" +hp.getRequestLine());
HttpResponse hr=hc.execute(hp);
HttpEntity he=hr.getEntity();
if(!(hr.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
System.out.println("Uploaded");
}
else{
System.out.println("Failed");
}
System.out.println(hr.getStatusLine());
if (he != null) {
System.out.println(EntityUtils.toString(he));
}
if (he != null) {
he.consumeContent();
}
hc.getConnectionManager().shutdown();
//这是正确的php代码
<?php
$uploads_dir='/Home';
if(is_uploaded_file($_FILES['userfile']['tmp_name'])){
$dest=$_FILES['userfile']['name'];
echo "File" .$_FILES['userfile']['name'] ."uploaded file successfully to
$uploads_dir/$dest";
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], "$uploads_dir/$dest");
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES);
}
?>
您的代码显示:
if(!(hr.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
^^^
+--- Notice the ! (not)
改为:
if((hr.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
如果状态为200,上传确实正常,因此它必须等于状态行以表示“上传”。您的代码说“上传”必须与“上传”不同。您是否阅读了错误消息并查看了它们所指的行?这是基本语法检查。已更正“文件”拼写错误,但仍然存在问题。您正在尝试访问Windows计算机上的文件夹/Home/
。你能解释一下你认为那应该是什么文件夹吗?它存在吗?所以你有一个警告;这不是一个错误。文件上传有效吗?