为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
梵蒂冈之花 2023-10-15 16:03:00
我在 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);但仍然没有什么区别。编辑2ServerRequestInterface 的实例代表服务器端的请求。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);但仍然没有运气。我缺少什么?如何更改请求以便正确发送文件?
查看完整描述

1 回答

?
偶然的你

TA贡献1841条经验 获得超3个赞

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



查看完整回答
反对 回复 2023-10-15
  • 1 回答
  • 0 关注
  • 55 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信