phplumenguzzlepsr-7buzz

Guzzle PSR7 request with multipart/form-data


I created a simple API in Lumen (application A) which:

public function apiMethod(ServerRequestInterface $psrRequest)
{
    $url = $this->getUri();

    $psrRequest = $psrRequest->withUri($url);

    $response = $this->httpClient->send($psrRequest);

    return response($response->getBody(), $response->getStatusCode(), $response->getHeaders());
}

The above code passes data to the application B for the query params, x-www-form-urlencoded, or JSON content type. However, it fails to pass the multipart/form-data. (The file is available in the application A: $psrRequest->getUploadedFiles()).

Edit 1

I tried replacing the Guzzle invocation with the Buzz

    $psr18Client = new Browser(new Curl(new Psr17Factory()), new Psr17Factory());
    $response = $psr18Client->sendRequest($psrRequest);

but still, it does not make a difference.

Edit 2

Instances of ServerRequestInterface represent a request on the server-side. Guzzle and Buzz are using an instance of RequestInterface to send data. The RequestInterface is missing abstraction over uploaded files. So files should be added manually http://docs.guzzlephp.org/en/stable/request-options.html#multipart

    $options = [];
    /** @var UploadedFileInterface $uploadedFile */
    foreach ($psrRequest->getUploadedFiles() as $uploadedFile) {
        $options['multipart'][] = [
            'name' => 'file',
            'fileName' => $uploadedFile->getClientFilename(),
            'contents' => $uploadedFile->getStream()->getContents()
        ];
    }

    $response = $this->httpClient->send($psrRequest, $options);

But still no luck with that.

What I am missing? How to change the request so files will be sent properly?


Solution

  • It seems that $options['multipart'] is taken into account when using post method from guzzle. So changing the code to the $response = $this->httpClient->post($psrRequest->getUri(), $options); solves the problem. Also, it is important not to attach 'content-type header.