You need to enable JavaScript to run this app. 如何通过Java向PHP服务端上传文件 接收还原失败如何解决
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Java向PHP服务端上传文件 接收还原失败如何解决

问题修复方案

核心错误原因

原有实现存在两处根本性错误:

  1. Java端将二进制字节数组作为普通POST参数发送时,HTTP传输会自动做字符编码转换,直接损坏原始字节,PHP的$_POST仅能接收编码后的字符串参数,无法拿到原始二进制数据
  2. PHP侧pack('C*', $bytes)用法完全错误,该方法需要传入多个整数参数,而$_POST['file']拿到的是已经损坏的字符串,不可能还原出原始文件字节

修复方案

方案一:使用HTTP标准文件上传格式(推荐)

采用multipart/form-data表单格式传输,这是HTTP上传文件的通用规范,两端适配成本最低。

Java客户端调整代码示例

File file = new File("本地文件路径");
String boundary = Long.toHexString(System.currentTimeMillis()); // 生成随机分隔符
URL url = new URL("PHP服务接口地址");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (OutputStream output = conn.getOutputStream();
     PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true)) {
    // 传递文件名参数
    writer.append("--" + boundary).append("\r\n");
    writer.append("Content-Disposition: form-data; name=\"fileName\"").append("\r\n");
    writer.append("\r\n").append(file.getName()).append("\r\n").flush();
    
    // 传递文件二进制内容
    writer.append("--" + boundary).append("\r\n");
    writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append("\r\n");
    writer.append("Content-Type: application/octet-stream").append("\r\n");
    writer.append("\r\n").flush();
    Files.copy(file.toPath(), output);
    output.flush();
    writer.append("\r\n").flush();
    
    // 表单结束标记
    writer.append("--" + boundary + "--").append("\r\n").flush();
}
// 后续处理服务端响应即可

PHP服务端调整代码示例

// 提前给上传目录配置读写权限
$uploadDir = "./upload/";
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
$fileName = $_POST['fileName'];
$targetPath = $uploadDir . $fileName;

// 直接通过$_FILES读取PHP自动解析的上传临时文件
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
    echo "上传成功";
} else {
    echo "上传失败,错误码:" . $_FILES['file']['error'];
}

方案二:原始字节流传输

如果不想使用表单格式,也可以直接把文件字节作为请求原始Body传输。

Java客户端调整

直接把读取到的byte[]写入POST请求的输出流,不要封装为普通POST参数,文件名可以放到自定义请求头X-File-Name中传递。

PHP服务端调整代码示例

$uploadDir = "./upload/";
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
// 直接读取请求原始Body得到原始字节
$fileBytes = file_get_contents('php://input');
// 从请求头取文件名
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
file_put_contents($uploadDir . $fileName, $fileBytes);

内容的提问来源于stack exchange,提问作者Sapu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 16:45:03