Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreiTelteu/171dc314f76de347cdcf1b47202b1e39 to your computer and use it in GitHub Desktop.
Save AndreiTelteu/171dc314f76de347cdcf1b47202b1e39 to your computer and use it in GitHub Desktop.
Laravel stream large file from disk with buffer.
<?php
// inspired by https://github.com/imanghafoori1/laravel-video
// if you need this for video, this does not support seek.
// laravel-video supports seek and chunks, so use that for video.
Route::get('/big-file-stream', function () {
$filePath = \Storage::disk('local')->path('video.mp4');
$fileStream = \Storage::disk('local')->readStream('video.mp4');
$fileSize = filesize($filePath);
$headers = [
'Content-type' => 'video/mp4',
// 'Content-type' => 'application/pdf',
// 'Content-Disposition' => 'attachment; filename=video.mp4', // if you need to force download
'Pragma' => 'no-cache',
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Expires' => '0',
'Content-Length' => $fileSize,
];
set_time_limit(0);
$end = $fileSize - 1;
$callback = function () use ($fileStream, $end) {
ob_get_clean();
$i = 0;
$buffer = 102400;
while (!feof($fileStream) && $i <= $end) {
$bytesToRead = $buffer;
if ($i + $bytesToRead > $end) {
$bytesToRead = $end - $i + 1;
}
$data = fread($fileStream, $bytesToRead);
echo $data;
flush();
$i += $bytesToRead;
}
fclose($fileStream);
};
return \Illuminate\Support\Facades\Response::stream($callback, 200, $headers)->send();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment