3

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?

oliverbj
  • 5,771
  • 27
  • 83
  • 178

2 Answers2

5

I would try withBody

$post = Http::withBody(file_get_contents($pathToFile), 'image/jpeg')
      ->withToken("<Token>")
      ->post($url);
Musa
  • 96,336
  • 17
  • 118
  • 137
1

Below code works for me, I'm trying to make a put request of a zip file I created, which is not path of the below code but below code illustrate how I'm able to get zip file full path and make use of it with withBody function and it works.

$zipFileName = 'public/memes/' . Str::random(11) . ".zip";
$zipFilePath = Storage::path($zipFileName);
// e.g. C:/laragon/www/laravel-project/storage/app/public/memes/xl26SNa6p3h.zip

Http::withBody(file_get_contents($zipFilePath), 'application/zip')
->withToken($token)
->put($url);

I hope it helpful.