Reputation: 1396
I want to be able to serve a file, located at any path on the server's filesystem that PHP/Apache has permission to read, as if it was in Laravel's public
folder.
Let's say I have a local directory on my server /var/directory/
that contains two files:
/var/directory/abc.jpg
/var/directory/xyz.jpg
Now, how can I make these files accessible via something like:
https://example.com/media/abc.jpg
https://example.com/media/xyz.jpg
I think I need a controller that handles routes for /media/{filename}
. It's fairly straight forward to then check if said file exists on disk in /var/directory/
and read it into PHP.
So the real question is: how I read these files efficiently and then serve them as a response to a get request? The solution should be as efficient as possible so that it works for larger files (10s to 100s of MB).
Upvotes: 3
Views: 3080
Reputation: 1396
I figured it out by myself. I must say, the solution is embarassingly simple.
I have all files indexed in the DB, so I can make use of route model binding. If that isn't the case for you, you'd need to look up if the file exists on disk manually.
Route::get('/media/{file:id}', FileDownloadController::class);
Then, all it takes is:
public function __invoke(File $file)
{
return response()->file($file->path);
}
Or this if a download prompt should be raised:
public function __invoke(File $file)
{
return response()->download($file->path);
}
Upvotes: 2