我创建了一个名为uploads
的文件夹,它与app
文件夹处于同一级别。如何使用像URL::to
这样的 Laravel 助手来获取其中的文件路径?
虽然上面的注释是正确的(浏览器不能直接访问这些文件) - 您仍然可以通过函数提供对这些文件的链接访问。
诀窍是使用 php 函数 readfile()
这允许您保护文件,并对其应用权限 - 即只有某些用户可以访问文件,用户只能访问自己的文件等。
这是允许登录用户访问文件的一种方法示例
像这样的路线:
Route::get('/view/{$file}', ['as' => 'viewfile', function($file) {
// Ensure no funny business names to prevent directory transversal etc.
$file = str_replace ('..', '', $file);
$file = str_replace ('/', '', $file);
// now do the logic to check user is logged in
if (Auth::check())
{
// Serve file via readfile() - we hard code the user_ID - so they
// can only get to their own files
readfile('../uploads/'.Auth::user()->id.'/'.$file);
}
}]);
然后在某处的视图文件中,您可以像这样链接到该文件:
<p>Here is a link to your file: {{ URL::route('viewfile', ['your_file_name.jpg']) }}</p>