【问题标题】:Guzzle PSR7 request with multipart/form-data带有多部分/表单数据的 Guzzle PSR7 请求
【发布时间】:2020-08-20 23:03:31
【问题描述】:

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

  • 接收 PSR-7 请求接口
  • 替换对应用程序 B 的请求的 URI
  • 并通过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

我尝试将 Guzzle 调用替换为 Buzz

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

但仍然没有运气。

我错过了什么?如何更改请求以便正确发送文件?

【问题讨论】:

    标签: php lumen guzzle psr-7 buzz


    【解决方案1】:

    似乎在使用 guzzle 的 post 方法时考虑了 $options['multipart'] 。因此将代码更改为$response = $this->httpClient->post($psrRequest->getUri(), $options); 即可解决问题。 另外,重要的是不要附加'content-type header。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 2016-12-17
      • 2012-03-16
      • 2016-11-11
      相关资源
      最近更新 更多