Skip to content
Advertisement

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 GuzzleHttpPsr7MultipartStream::addElement() must be of the type array, string given, called in vendorguzzlehttppsr7srcMultipartStream.php on line 70 and defined in vendorguzzlehttppsr7srcMultipartStream.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?

Advertisement

Answer

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')
                ]
            ]
        ]);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement