php - 在 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->get
CakePHP 将整个响应存储在内存中。这就是为什么我得到一个内存耗尽错误。
我知道我在这里缺乏一点理解。任何帮助表示赞赏:)
解决方案
最后我找到了解决方案:
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;
}
推荐阅读
- laravel - 车辆与价格之间的雄辩关系
- node.js - AWS Lambda:同步调用流
- java - Kafka Connect:Rest API Source Connector 连接被拒绝
- php - 注释路线并在内部扩展现有方法
- python - 在 Mac 上安装 GDAL 后,jupyter-lab 中没有名为“gdal”的模块
- javascript - AWS Amplify JS 如何选择 Cognito 用户组?
- android - 在将数据发送到磁电机服务器时,使用@FormUrlEncoded 调用 Magneto API 进行改造
- r - 将数字向量转换为 R 中的连续整数
- c# - 通用值在列表中分配数据类型
- c - 复制匿名管道而不是标准输出并通过它传递参数