Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
On the other hand I created a 700 MB file and tried to get its content using code

file_get_contents($file)

error was thrown.

Allowed memory size of XXX bytes exhausted (tried to allocate YYY bytes)

I am not sure how StreamedResponse and setCallback function worked here. Can someone explain?

like image 801
Anurag Rana Avatar asked May 13 '26 07:05

Anurag Rana


1 Answers

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).

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.

And you will have to do this is a loop, that will update the StreamResponse with what you have read.

like image 179
Dric512 Avatar answered May 14 '26 21:05

Dric512



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!