使用PHP从Java客户端上传文件不起作用


Uploading file From Java Client Using PHP is not working

我在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);

首先我要查看$_FILES['userfile']['error']的值

有关错误代码的描述,请参阅本手册页面:

http://php.net/manual/en/features.file-upload.errors.php