Download large data from browser
Hi there,
I tried to send large data to stream response, but when I send request from browser,
the browser didn't open file dialog download until method $stream->end() was called.
Can someone please give me a simple example on how I'm supposed to open file dialog download the moment the method $stream->write($chunk) call, like echo($chunk); ob_flush(); in apache ?
Many thanks!
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
$stream = new ThroughStream();
// total ~ 2GB
while (!empty_data()) {
$chunk = read_data();
$stream->write($chunk);
}
$stream->end();
return new Response(
Response::STATUS_OK,
array(
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => "attachment; filename=pnn",
'Content-Description' => 'File Transfer',
'Content-Transfer-Encoding' => 'binary',
'Connection' => 'Keep-Alive',
'Expires' => '0',
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Pragma' => 'public'
),
$stream
);
});
Hey @maituduy, thanks for bringing this up :+1:
As the documentation for the ThroughStream class says, it passes any data you write to it through to its readable end. That means you already wrote all the data when you get to your $stream->end(); which results in $stream being empty.
Also note that if the example above worked as you expected, it would result in 2GB being kept in your memory.
I am also not sure if you're working with the filesystem when reading your data. If this is the case, keep in mind that the filesystem is inherently blocking, so we have no choice to be blocking as well.
Maybe take a look at clue/framework-x, we're currently working on the same topic there. You could also use the reactphp/filesystem component, but note that this component is still experimental.
I hope this helps.
I'll assume this is resolved and will close this for now, please feel free to report back otherwise :+1: