Created
September 9, 2021 07:21
-
-
Save fjahn/c1516aab65da545b71c90a16cbfd6ccf to your computer and use it in GitHub Desktop.
Laravel Stream Download
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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