Reputation: 6098
I want to store files (pdfs, images, videos) that can only be accessed by Laravel. This would force a user to use the website rather than a url.
How can I achieve this? And are there best practices to doing this?
thank you!
Here is my code:
public static function downloadFile($id){
$file = FileManager::find($id);
//$file->location = ../app/storage/file/dam04/2-2/manual.pdf
//file->type = pdf
//file->name = instructor manual
$headers = array(
'Content-Type:'.mime_content_type($file->location),
);
return Response::download($file->location, $file->name.'.'.$file->type, $headers);
//exit;
}
I cannot get this to fire. the files are located in app/storage/.
I could really use some advice as to why this won't work. Thanks,
Upvotes: 0
Views: 1702
Reputation: 87789
You can use Response::download()
:
Create a router:
Route::get('/files/{fileName}', 'FileServerController@download');
And in your controller you do
class FileServerController extends Controller {
public function download($fileName)
{
if (file_exists("$basepath/$fileName"))
{
return Response::download("$basepath/$fileName");
}
return Redirect::route('home')->withMessage('file not found');
// or return Response::make('File not found', 404);
}
}
You can auth filter your route:
Route::get('/files/{fileName}', ['before' => 'auth', 'uses' => 'FileServerController@download']);
And you can use intended() to start downloading a file as soon as your user is logged in:
if (Auth::attempt(...))
{
return Redirect::intended('home');
}
Upvotes: 2