我正在将旧系统迁移到新版本的 Laravel,但我的一个请求出现问题...
基本上,根据此请求,我收到任何文件并将其转发给用户。这是使用 Guzzle
的旧版本:
use Symfony\Component\HttpFoundation\StreamedResponse;
public function getMedia($media)
{
try {
$response = $this->client->get('media/' . $media, [
'stream' => true
]
);
$contentType = $response->getHeader('Content-Type');
$body = $response->getBody();
$stream = new StreamedResponse(function () use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$stream->headers->set('Content-Type', $contentType);
return $stream;
} catch (ClientException $e) {
return response()->json([
'errors' => json_decode($e->getResponse()->getBody()->getContents())->errors,
'message' => 'Unfortunately we could not find the requested file'
], 404);
}
}
以及我尝试编写的新代码,但没有成功:
use Symfony\Component\HttpFoundation\StreamedResponse;
public function getMedia($media)
{
$response = Http::withOptions([
'stream' => true
])->get("media/{$media}");
$contentType = $response->header('Content-Type');
$body = $response->body();
$stream = new StreamedResponse(function () use ($body) {
while (!$body->eof()) {
echo $body->read(1024);
}
});
$stream->headers->set('Content-Type', $contentType);
return $stream;
}
有人知道如何解决这个问题吗?我不知道该怎么办了...
最佳答案
我知道,晚了 2 年,但我正在做类似的事情,你应该通过 psr 访问响应
而不是:
$body = $response->body(); // This try to return an string
使用这个:
$body = $response->toPsrResponse()->getBody(); // the guzzle response
然后你就可以使用你的普通代码
我希望有人会发现这很有用,
关于Laravel - 在新的 Http 客户端中使用 Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60552314/