php-http / guzzle6-adapter

Guzzle 6 HTTP adapter

Home Page:http://httplug.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Trying to send multipart

faustbrian opened this issue · comments

Hi,

I am building an API Client at the moment and I am trying to send a POST request with multipart data.

The data I am trying to send looks like the following.

array:1 [▼
  "multipart" => array:2 [▼
    0 => array:2 [▼
      "name" => "file"
      "contents" => stream resource @135 ▶} // contents is fopen($file, 'r')
    ]
    1 => array:2 [▼
      "name" => "apikey"
      "contents" => "mysecretapikey"
    ]
  ]
]

Using Guzzle 6 Standalone I would do it like this and this works just fine.

$guzzle = new \GuzzleHttp\Client($options);

$response = $guzzle->request('POST', $uri, ['multipart' => $body]);

dump($response->getBody()->getContents());

Now when trying to use the adapter I came up with this.

$guzzle = new \GuzzleHttp\Client($options);

$adapter = new \Http\Adapter\Guzzle6\Client($guzzle);

// For form_params I could do ...
// $body = \GuzzleHttp\Psr7\stream_for(http_build_query($params));
// but how am I going to add multipart data to a request?
$request = new \GuzzleHttp\Psr7\Request($method, $uri, $headers, $body);

$pluginClient = new HttpMethodsClient(
    new PluginClient($adapter, $this->plugins),
    $this->messageFactory
);

$response = $adapter->sendRequest($request);

Sending the request with the adapter always results in a 403 Forbidden because the multipart data gets useless after building it with stream_for. So how do I send a multipartrequest with this adapter since there is no request method?

@faustbrian You can take a look at the MultipartStreamBuilder from the php-http/multipart-stream-builder package.

Thanks, that also led me to finding this solution if you want to leverage Guzzle itself.

$stream = new \GuzzleHttp\Psr7\MultipartStream($body, uniqid());

$response = $pluginClient->send($method, $uri, $headers, $stream);