Skip to content

Instantly share code, notes, and snippets.

@fjahn
Created September 9, 2021 07:21
Show Gist options
  • Save fjahn/c1516aab65da545b71c90a16cbfd6ccf to your computer and use it in GitHub Desktop.
Save fjahn/c1516aab65da545b71c90a16cbfd6ccf to your computer and use it in GitHub Desktop.
Laravel Stream Download
<?php
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Similar to Storage::download, but serves the file as a stream.
*
* Stolen and adapted from stackoverflow.com/questions/44965777/laravel-5-file-downloads-stream-or-download
*/
function stream_download(string $asset): StreamedResponse
{
abort_unless(Storage::exists($asset), Response::HTTP_NOT_FOUND);
return response()->stream(function () use ($asset) {
$stream = Storage::readStream($asset);
fpassthru($stream);
if (is_resource($stream))
fclose($stream);
}, headers: [
'Content-Type' => Storage::mimeType($asset),
'Content-Length' => Storage::size($asset),
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment