我在Java中有以下上传方法:
public void uploadFile() throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://myurl/uploadper.php");
File file = new File("C:/Users/mislam/Desktop/perfimg/0.jpg");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
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();
}
我有以下php文件
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['userfile']['name']);
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['userfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
我收到以下输出
executing request POST http://reactor.ctre.iastate.edu/uploadper.php
HTTP/1.1
HTTP/1.1 200 OK
There was an error uploading the file, please try again!
表示与服务器的通信成功但无法上传。 PHP没有上传文件的原因是什么? java代码有什么问题吗?
修改 重写多部分实体的代码后,我在服务器中获取该文件但上传操作无效:
HttpEntity httpEntity = MultipartEntityBuilder.create()
.addBinaryBody("userfile", file, ContentType.create("image/jpeg"), file.getName())
.build();
httppost.setEntity(httpEntity);
答案 0 :(得分:1)
首先我要看一下$ _FILES的价值[&#39; userfile&#39;] [&#39;错误&#39;]
有关错误代码的说明,请参阅本手册页: