首页 > 解决方案 > 通过 Guzzle 客户端发送图像

问题描述

如何通过 Guzzle(PHP) 发送带有图像的 POST 请求?

通过 curl,一切都应该是这样的:

$ curl -X POST "https://example.com.ua/api/add" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "files=@image.png;type=image/png" -F "test=test"

我试过了:

$multipart = [
    [
        'name'     => 'test',
        'contents' => 'test'
    ], [
        'name'     => 'files',
        'contents' => fopen(public_path($this->user->imagePath()), 'r'),
        'filename' => 'filename' . '.' . File::extension(public_path($this->user->imagePath())),
        'headers' => ['Content-Type' => 'image/jpeg']
        ],
    ];

$guzzleClient->request(
    'POST',
    self::BASE_URL . '/add',
    array_merge([RequestOptions::MULTIPART => $multipart], ['headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'multipart/form-data'
    ]])
);

一切由

 <a href="http://docs.guzzlephp.org/en/stable/request-options.html#multipart">docs</a>

调试后外部 API 告诉我 -field "files" missed Content-Type: image/jpeg

我究竟做错了什么?

如何在 Guzzle 中执行此查询?

标签: phpguzzle

解决方案


推荐阅读