可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.