PHP - 带有二进制正文数据的 POST 请求 - 适用于 CURL,但不适用于 Laravel

问题描述 投票:0回答:2

我有下面的第 3 方 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, 1);
curl_setopt($ch, 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);

以上没有按预期工作。第 3 方 API 服务返回 400 响应并告诉我它无法读取图像文件。

我做错了什么?

php laravel guzzle php-curl
2个回答
5
投票

我会尝试

withBody

$post = Http::withBody(file_get_contents($pathToFile), 'image/jpeg')
      ->withToken("<Token>")
      ->post($url);

0
投票

下面的代码对我有用,我正在尝试对我创建的 zip 文件发出放置请求,这不是下面代码的路径,但下面的代码说明了我如何能够获取 zip 文件的完整路径并利用它具有 withBody 功能并且有效。

$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);

希望对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.