Guzzle ~6.0 multipart and form_params

I googled similar problem and write here advice:

Do not set header "Content-Type" manually for multipart request.


    $body['query'] = $request->input();
        if($_FILES)
         {
            $filedata = [];
            foreach( $_FILES as $key => $file){               
                if(!($file['tmp_name'] == '')){
                    $file['filename'] = $file['name'];
                    $file['name']=$key;
                    $file['contents'] = fopen($file['tmp_name'], 'r');
                    $file['headers'] = array('Content-Type' => mime_content_type($file['tmp_name']));
                }
                else{
                    $file['contents'] = '';
                }
                array_push($filedata, $file);
            }
        $body['multipart'] = $filedata;
        }

        $header= ['headers'=>[
                    'User-Agent' => 'vendor/1.0',
                    'Content-Type' =>'multipart/form-data',
                    'Accept'     => 'application/json',
                    'Authorization' => "Authorization: Bearer ".$token,
                ]];
        $client = new Client($header);
        $response = $client->POST($url, $body);
        $response=json_decode($response->getBody());

I got there too, but unfortunately it does not work if you have multidimensional params array. The only way i got it to work is if you send the form_paramaters as query parameters in the array:

$response = $client->post('http://example.com/api', [
    'query' => [
        'name' => 'Example name',
    ],
    'multipart' => [
        [
            'name'     => 'image',
            'contents' => fopen('/path/to/image', 'r')
        ]
    ]
]);

I ran into the same problem. You need to add your form_params to the multipart array. Where 'name' is the form element name and 'contents' is the value. The example code you supplied would become:

$response = $client->post('http://example.com/api', [
    'multipart' => [
        [
            'name'     => 'image',
            'contents' => fopen('/path/to/image', 'r')
        ],
        [
            'name'     => 'name',
            'contents' => 'Example name'
        ]
    ]
]);

Tags:

Php

Curl

Guzzle