Skip to content

Instantly share code, notes, and snippets.

@coreymcmahon
Created October 26, 2021 12:47
Show Gist options
  • Save coreymcmahon/28a41967c75058342d24b0eaba80dc8d to your computer and use it in GitHub Desktop.
Save coreymcmahon/28a41967c75058342d24b0eaba80dc8d to your computer and use it in GitHub Desktop.
Stream a handle (Laravel + Flysystem)
<?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