在PHP的curl中指定multipart / form-data的每个部分的Content-Type

时间:2010-07-09 00:33:00

标签: php curl multipartform-data

如何指定multipart / form-data请求的特定部分的内容类型?图像的内容类型以application/octet-stream发送,但服务器期望它为image/jpeg。这会导致服务器拒绝我的请求。

$data["file"] = "@/image.jpg";
$data["title"] = "The title";
$data["description"] = "The description";

//make the POST request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);

这是请求的相关部分:

Content-Type: multipart/form-data; boundary=----------------------------fc57f743c490

------------------------------fc57f743c490
Content-Disposition: form-data; name="file"; filename="NASA-23.jpg"
Content-Type: application/octet-stream

我希望它是:

Content-Type: multipart/form-data; boundary=----------------------------fc57f743c490

------------------------------fc57f743c490
Content-Disposition: form-data; name="file"; filename="NASA-23.jpg"
Content-Type: image/jpeg

1 个答案:

答案 0 :(得分:5)

你会做这样的事情,

$data["file"] = "@/image.jpg;type=image/jpeg";

//make the POST request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);