phpbddbehatguzzle

Guzzle 6 send multipart data


I'd like to add some data to a Guzzle Http Request. There are file name, file content and header with authorization key.

$this->request = $this->client->request('POST', 'url', [
    'multipart' => [
        'name' => 'image_file',
        'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
        'headers' =>
            ['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
            ]]);

but I get error

Catchable Fatal Error: Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string given, called in vendor\guzzlehttp\psr7\src\MultipartStream.php on line 70 and defined in vendor\guzzlehttp\psr7\src\MultipartStream.php line 79

In Guzzle 6 documentation is something like this: http://docs.guzzlephp.org/en/latest/request-options.html#multipart

Who knows where I made a mistake?


Solution

  • Here is the solution. Header with access token should be outside multipart section.

    $this->request = $this->client->request('POST', 'request_url', [
                'headers' => [
                    'Authorization' => 'Bearer access_token'
                ],
                'multipart' => [
                    [
                        'Content-type' => 'multipart/form-data',
                        'name' => 'image_file',
                        'contents' => fopen('image_file_url', 'r')
                    ]
                ]
            ]);