Guzzle ~6.0 多部分和 form_params

Guzzle ~6.0 multipart and form_params

我正在尝试上传文件并同时发送 post 参数,如下所示:

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

然而,我的 form_params 字段被忽略了,只有多部分字段出现在我的 post 正文中。我可以用 guzzle 6.0 发送两者吗?

我运行遇到了同样的问题。您需要将 form_params 添加到 multipart 数组。其中 'name' 是表单元素名称,'contents' 是值。您提供的示例代码将变为:

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

我也到了那里,但不幸的是,如果你有多维参数数组,它就不起作用了。我让它工作的唯一方法是将 form_paramaters 作为数组中的查询参数发送:

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

我用谷歌搜索了类似的问题并在这里写下建议:

不要为多部分请求手动设置 header“Content-Type”。

    $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());