Created
October 26, 2021 12:47
-
-
Save coreymcmahon/28a41967c75058342d24b0eaba80dc8d to your computer and use it in GitHub Desktop.
Stream a handle (Laravel + Flysystem)
This file contains hidden or 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 | |
namespace Controllers; | |
class FilesController | |
{ | |
/** | |
* Add a route definition: | |
* $router->get("assets/{any}", "FilesController@index")->where('any', '.*'); | |
*/ | |
public function index(string $any) | |
{ | |
$path = "assets/{$any}"; | |
try { | |
// Replace s3 with relevant Flysystem driver | |
$metadata = \Storage::disk('s3')->getMetadata($path); | |
} catch (\Exception $ex) { | |
// Above call will throw an exception if file does not exist | |
abort(404); | |
} | |
$stream = \Storage::disk('s3')->getStream($path); | |
$passthru = function () use ($stream) { | |
fpassthru($stream); | |
}; | |
return response()->stream($passthru, 200, [ | |
'Content-Type' => $metadata['type'], | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment