Guzzle ~6.0 multipart and form_params

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

I am trying to upload file and send post parameters at the same time like this:

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

However my form_params fields are ignored and only the multipart fields are present in my post body. Can I send both at all with guzzle 6.0 ?

回答1:

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


回答2:

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


回答3:

According the official documentation, multipart and form_params options cannot be used at the same time. You will need to use one or the other.

Use form_params for application/x-www-form-urlencoded requests, and multipart for multipart/form-data requests.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!