首页 > 解决方案 > Laravel/Guzzle - POST 二进制文件内容

问题描述

我正在尝试向第 3 方 API 发出简单的 POST 请求。API 接受文件作为 BODY 参数。具体来说,文件内容必须是二进制的:

在此处输入图像描述

我已经使用 Postman 成功发布到这个第 3 方 API,正文配置如下:

在此处输入图像描述

上传文件时,我使用的是 Laravel。这是代码:

//$document is a class of "UploadedFile"
$tempfile = Storage::disk('local')->putFile('/temp', $document);

然后我只是尝试使用 Guzzle 发布此文件:

use Illuminate\Support\Facades\Http;

$filepath = storage_path('app/' . $tempfile);
$post = Http::attach('file', file_get_contents($tempfile), 'myfile.pdf')->post('example.org')->json());

但是,第 3 方 API 无法将其识别为 PDF 文件:

内容类型必须是 application/vnd.hypatos.ocr+json application/pdf image/tiff image/jpeg image/png text/xml application/xml 之一

与我在 Postman 中发送的请求相比,我做错了什么?这是我试图发布到 API 的完全相同的文件。

标签: phplaravelguzzle

解决方案


您是否尝试过Content-Type像这样在请求标头中指定您的

Http::attach('file', file_get_contents($tempfile), 'myfile.pdf')->withHeaders([
    'Content-Type' => 'application/pdf',
])->post('example.org')->json();

推荐阅读