问题描述
我将图像发布到下面的第三方API中。
它们要求标头的内容类型必须设置为:Content-Type: image/jpeg
,并且主体必须包含实际图像的二进制数据。
下面,我正在使用PHP中的cURL发出此请求-这很好:
$url = "examle.org/images";
$pathToFile = "myfile.jpeg";
$auth = "Authorization: Bearer <Token>";
$auth = "Authorization: Bearer " . $this->token;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POST,CURLOPT_POSTFIELDS,file_get_contents($pathToFile));
curl_setopt($ch,CURLOPT_HTTPHEADER,['Content-Type: image/jpeg',$auth]);
$result = curl_exec($ch);
以上使用cURL的POST正常工作:我收到200响应成功错误。我想,为了使其更像“ Laravel”,我将使用Laravel的HTTP Facade(Guzzle):
$post = Http::withHeaders(['Content-Type' => 'image/jpeg'])
->withToken("<Token>")
->attach('file',file_get_contents($pathToFile),'myfile.jpeg')
->post($url);
以上内容无法正常工作。第三方API服务返回400响应,并告诉我它无法读取图像文件。
我在做什么错了?
解决方法
我会尝试withBody
$post = Http::withBody(file_get_contents($pathToFile),'image/jpeg')
->withToken("<Token>")
->post($url);