gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:34:17 24 4
gpt4 key购买 nike

我在 Java 中有以下 uploader 方法:

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

关于java - 使用 PHP 从 Java 客户端上传文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com