首页 > 解决方案 > 在 CakePHP 中流式传输响应

问题描述

我希望 CakePHP 将下载流式传输到浏览器。流的内容通过 API 提供。

因此,CakePHP 向该 API 发出请求,获得带有文件的响应,并且必须将该响应流式传输到浏览器。

这是我到目前为止得到的:

public function getDownload() {

    // do other things

    $http = new Client([
            'headers' => [
                'accept' =>'application/octet-stream'
            ]
        ]);

    $response = $http->get($this->url,[]);

    // first try
    // $stream = new CallbackStream(function () use ($response) {
    //     return $response;
    // });
    // $response = $response->withBody($stream);

    // second try
    // $stream = new CallbackStream($http->get($this->url,[])->getData());
    // $response = $response->withBody($stream);

    return $response;
}

通过此设置,我可以下载小文件。我需要流的原因是,因为 API 可以发送高达 10GB 的文件。我的猜测是,$http->getCakePHP 将整个响应存储在内存中。这就是为什么我得到一个内存耗尽错误。

我知道我在这里缺乏一点理解。任何帮助表示赞赏:)

标签: phpcakephpcakephp-3.0

解决方案


最后我找到了解决方案:

public function getDownload($url) {

$opts = array(
'http'=>array(
    'method'=>"GET",
    'header'=>"accept: application/octet-stream\r\n"
    )
);

$context = stream_context_create($opts);
$response = new Response();

$file = fopen($url, 'r',false, $context);

$stream = new CallbackStream(function () use ($file) {
    rewind($file);
    fpassthru($file);
    fclose($file);
});

$response = $response->withBody($stream);
return $response;
}

推荐阅读