I have below 3rd party API that I am posting images to.
They require that the header's content-type must be set to: Content-Type: image/jpeg
, and that the body contains the binary data of the actual image.
Below I am making this request using cURL in PHP - this works fine:
$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, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($pathToFile));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: image/jpeg', $auth]);
$result = curl_exec($ch);
The above POST using cURL works fine: I get a 200-response success error back. I thought, in order to make it more "Laravel-like", I would use Laravel's HTTP facade (Guzzle):
$post = Http::withHeaders(['Content-Type' => 'image/jpeg'])
->withToken("<Token>")
->attach('file', file_get_contents($pathToFile), 'myfile.jpeg')
->post($url);
The above does not work as expected. The 3rd party API services return a 400 response and tells me that it cannot read the image file.
What am I doing wrong?
I would try withBody
$post = Http::withBody(file_get_contents($pathToFile), 'image/jpeg')
->withToken("<Token>")
->post($url);