我想在PHP中使用multipart/form-data头部使用cURL发布图像,因为接收方API希望图像作为多部分表单发送。
我没有问题与API进行其他请求的通信;只有发布图像是个问题。
我在客户端使用这个表单:
<form action="http://myServerURL" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="Submit">
</form>
以下是我正在向其发布此数据(在此我正尝试将此数据转发到API)的服务器:
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $imgRawData); // <-- raw data here hm?
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookieJar);
curl_setopt( $ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1); <-- using this as I wanted to check if HTTPHEADER is set
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data')); <-- setting content-type header?
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
// i get response from the server
$response = curl_exec( $ch );
// with this I can check what kind of content type the last request had?
$requestContentType = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);
echo "<br>request Content Type was:".$requestContentType."<br>";
curl_close($ch);
echo "<br><b>SERVER POST IMAGE RESPONSE:</b><br>";
echo $response;
使用下面的代码,我可以查看我的请求头:
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
var_dump(curl_getinfo($ch));
现在请求头中的内容类型已经正确显示。但是似乎图像未按API预期正确发送。不幸的是,我没有访问API的权限...
非常感谢您的任何帮助。