PHP可能会错误地将JPEG数据解释为包含“&”字符或其他令其混淆的表单数据,从而填充$_POST数组。如果你手动读取输入流而不是依赖于$_POST,你应该能够恢复数据。我编写了一些快速代码来尝试复制您的问题并对其进行测试:
client.php
这段代码模拟了您的客户端;它只是读取一个JPEG文件,并将其原始内容写入POST请求。
$url = 'http://localhost/server.php';
$input = __DIR__ . '/input.jpg';
$parts = parse_url($url);
$sock = fsockopen($parts['host'], 80);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".(filesize($input) + strlen("rawImageData="))."\r\n";
$out.= "\r\n";
$out.= "rawImageData=";
fwrite($sock, $out);
$fd = fopen($input, 'r');
stream_copy_to_stream($fd, $sock);
fclose($fd);
fclose($sock);
server.php(版本1)
这尝试使用$_POST
值,就像你的代码一样。
$tmp = "/tmp/output.jpg";
file_put_contents($tmp, $_POST['rawImageData']);
server.php(版本2)
此文件从POST请求体中读取原始输入流。
$tmp = "/tmp/output.jpg";
$fd = fopen('php://input', 'r');
fread($fd, strlen("rawImageData="));
$out = fopen($tmp, 'w');
stream_copy_to_stream($fd, $out);
fclose($out);
fclose($fd);
我使用维基百科上大小约为10k的JPEG文件作为input.jpg
。
结果
服务器版本1仅向output.jpg
写入约50个字节,当我尝试使用查看器打开它时,会出现损坏的JPEG错误。服务器版本2写入了完整的10k字节,我的JPEG查看器可以正常显示图片。
mb_convert_encoding()
吗? - Darrenfile_put_contents($filePath, file_get_contents('php://input'));
,然后自己删除非图像数据。 - Steve H