Laravel - 在新的 Http 客户端中使用 Stream

标签 laravel laravel-7

我正在将旧系统迁移到新版本的 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/

相关文章:

php - 在 laravel 5.6 中迁移时如何检查 mongo 集合是否存在?

php - 如何使用数据库中没有的自定义属性保存模型? -Laravel 5.4

laravel - 我的Docker镜像中不存在vendor文件夹

Laravel Blade 指令添加额外的引号

php - 发出 POST 请求时,Laravel WebSocket 出现 Pusher 错误

laravel - 为集合分页,Laravel

php - 按自定义顺序对 Laravel 集合进行排序,而不是 asc 或 desc

javascript - 如何在 vue 组件中使用 Maatwebsite 导入 excel 文件?

Laravel关系: A division has many ranks,一个等级有1个分区,一个用户只有1个等级

cors - Laravel Sanctuary : blocked by CORS policy with Nuxt Auth module