3
votes

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?

3
Thanks, however, these tutorials are to the previous Guzzle version. I'm using latest version.user3036307
The first link uses guzzle 6BentCoder

3 Answers

8
votes

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')
                ]
            ]
        ]);
6
votes

As per the docs, "The value of multipart is an array of associative arrays", so you need to nest one level deeper:

$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']
        ]
    ]
]);
0
votes

try this works for me

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;

$this->client = new Client([
        'base_uri' => 'https://baseurl'
    ]);

$body = Utils::tryFopen($tempPath . $fileName, 'r');
$res = $this->client->request(
                 'POST',
                 'url',
                  [
                     'headers' => [
                        ...
                     ],
                     'body' => $body
                  ]
            );