Guzzle 6 send multipart data

12,156

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']
        ]
    ]
]);
Share:
12,156
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    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?

  • iainn
    iainn about 8 years
    @PrzemekGawłowski I don't mean you just need to format the code differently, you need to give the multipart option "an array of associative arrays". In your code you're just giving it a single associative array. Wrap some extra square brackets around it, as in my example.
  • Admin
    Admin about 8 years
    You're right, my bad. So now i got this error message :-( Catchable Fatal Error: Object of class GuzzleHttp\Psr7\Response could not be converted to string in features\bootstrap\FeatureContext.php line 246
  • iainn
    iainn about 8 years
    Can't say for sure without seeing the code, but it sounds like you're missing a call to the getBody() method, e.g. echo (string) $response->getBody();
  • Admin
    Admin about 8 years
    $response->getBody(); Server error: "POST my_url" resulted in a "500 Internal Server Error" response: {"message":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more (tr uncated...) (GuzzleHttp\Exception\ServerException)
  • iainn
    iainn about 8 years
    Now it just sounds like you're sending a request the server doesn't understand. We're getting quite off-topic though.