Guzl ~ 6.0 multipart and form_params

I am trying to upload a file and send message parameters at the same time as follows:

$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 multipart fields are present in my mail body. Can I send both using gzzle 6.0?

+6
source share
3 answers

I ran into the same problem. You need to add form_params to the multipart array. Where "name" is the name of the form element and "content" is the value. The example code you provided will be as follows:

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

I got there too, but unfortunately this will not work if you have a multi-dimensional params array. The only way to make it work if you send form_paramaters as request parameters in an array:

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

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

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

+1
source

Source: https://habr.com/ru/post/988515/


All Articles