问题描述
我在Lumen(应用程序A)中创建了一个简单的API,该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());
}
以上代码将数据传递给应用程序B,以获取查询参数,x-www-form-urlencoded或JSON内容类型。但是,它无法传递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);
但是仍然没有运气。
我缺少什么?如何更改请求,以便文件能够正确发送?
解决方法
在使用guzzle的post方法时,似乎已经考虑到$ options ['multipart']了。因此,将代码更改为$response = $this->httpClient->post($psrRequest->getUri(),$options);
可解决此问题。
另外,重要的是不要附加“内容类型标头”。