简体   繁体   English

StreamedResponse 如何工作?

[英]How does StreamedResponse work?

I wrote below code in a controller action.我在控制器操作中编写了以下代码。

$response = new StreamedResponse();  
$i = -999999;  
$response->setCallback(function () {  
    while($i < 999999){  
        echo '{"G1ello":"hualala"}';  
        $i = $i + 1;  
    }  
});  
$filename = "Data.json";  
$contentDisposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('Content-Disposition', $contentDisposition);
return $response;

This way I was able to download 1.7 GB JSON file.这样我就可以下载 1.7 GB 的 JSON 文件。
On the other hand I created a 700 MB file and tried to get its content using code另一方面,我创建了一个 700 MB 的文件并尝试使用代码获取其内容

file_get_contents($file)

error was thrown.错误被抛出。

Allowed memory size of XXX bytes exhausted (tried to allocate YYY bytes)已用完 XXX 字节的允许内存大小(尝试分配 YYY 字节)

I am not sure how StreamedResponse and setCallback function worked here.我不确定 StreamedResponse 和 setCallback 函数在这里是如何工作的。 Can someone explain?有人可以解释一下吗?

The problem is cleary not about the StreamResponse but about the fact that you're trying to read the 700MB file to memory at one (Before returning in by small parts).问题很明显不是关于StreamResponse而是关于您试图一次将 700MB 文件读取到内存的事实(在由小部分返回之前)。

Depending on the file you read, you should read it by chunks:根据您读取的文件,您应该分块读取:

  • If this is a text file, read it line by line for example如果这是一个文本文件,请逐行读取例如
  • If this is a binary file, you could use the same function, but use $maxlen and $offset to limit what you read each time.如果这是一个二进制文件,您可以使用相同的函数,但使用$maxlen$offset来限制您每次读取的内容。

And you will have to do this is a loop, that will update the StreamResponse with what you have read.并且您必须这样做是一个循环,它将使用您阅读的内容更新StreamResponse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM