我在 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);
解決問題。另外,重要的是不要附加“內容類型標頭”。
- 1 回答
- 0 關注
- 129 瀏覽
添加回答
舉報
0/150
提交
取消