使用 multipart/form-data 处理 PSR7 请求

我在 Lumen(应用程序 A)中创建了一个简单的 API,其中:

  • 接收PSR-7请求接口

  • 将请求的 URI 替换为应用程序 B

  • 并通过Guzzle发送请求。

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());

}

上面的代码将查询参数、x-www-form-urlencoded 或 JSON 内容类型的数据传递到应用程序 B。但是,它无法传递 multipart/form-data。(该文件可在应用程序 A: 中找到$psrRequest->getUploadedFiles())。

编辑1

我尝试用Buzz替换 Guzzle 调用

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

但仍然没有什么区别。

编辑2

ServerRequestInterface 的实例代表服务器端的请求。Guzzle 和 Buzz 使用 RequestInterface 的实例来发送数据。RequestInterface 缺少对上传文件的抽象。因此应该手动添加文件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);

但仍然没有运气。


我缺少什么?如何更改请求以便正确发送文件?


梵蒂冈之花
浏览 103回答 1
1回答

偶然的你

使用 guzzle 的 post 方法时似乎会考虑 $options['multipart'] 。因此更改代码即可$response = $this->httpClient->post($psrRequest->getUri(), $options);解决问题。另外,重要的是不要附加“内容类型标头”。
打开App,查看更多内容
随时随地看视频慕课网APP