2

假设我想制作一个应用程序,用户可以将私人文件上传到基于 laravel 的网站。我不想公开他们的文件,但我希望他们能够在登录后下载文件。

所以我需要验证他们是否已经登录,并且他们有正确的帐户 ID 来下载特定文件。如何创建此限制?

我一直在寻找http://laravel.com/docs没有成功,通过谷歌搜索我只能获得一些普通的 PHP 示例,但是集成到 laravel 中似乎很乱,你建议我用哪种方式这个?

我的头脑中的情况可能过于复杂,也许我可以在数据库中创建一个包含帐户 ID 和文件路径的表,并使用 Response::download($pathToFile); 并使用 .htaccess 限制上传的文件夹不允许?

(假设 laravel Response::download 方法绕过 .htaccess)但即使这项工作可能最好找到一种方法来做到这一点而无需 .htaccess 思想?

编辑 我想我只是将数据库中的文件存储为 blob,然后从那里加载它。这样我就可以轻松地进行授权验证。

4

3 回答 3

7

您所要做的只是将文件存储在私有目录中(例如。/app/files)并设置正确的标题。

    $name = 'name.zip';
    $file = '/app/files/name.zip';

    $header = array(
        'Content-Type' => 'application/octet-stream',
        'Content-Disposition' => 'attachment', 
        'Content-length' => filesize($file),
        'filename' => $name,
    );

    // auth code
    return Response::download($file, $name, $header);
于 2014-06-12T18:57:18.663 回答
1

我刚遇到这个,也许它也可以帮助别人。我用它来“保护”我的 PDF 文档,只允许登录用户使用。

我把我的文件放在storage/public 文件夹之外(所以没有一个是公众可以访问的)。Controller 受构造函数中的“auth”中间件保护。

public function grab_file($hash)
    {
        $file = Publication::where('hash', $hash)->first();

        if ($file) {
            return Response::download(storage_path('app/publications/' . $file->filename), null, [
                'Cache-Control' => 'no-cache, no-store, must-revalidate',
                'Pragma' => 'no-cache',
                'Expires' => '0',
            ], null);
        } else {
            return abort(404);
        }
}

路线是;

Route::get('/user/file/{hash}', 'UserController@grab_file');

Publication存储了对文件的哈希引用。这样,用户就无法“看到”实际文件的位置。

“无缓存”标头确保浏览器没有缓存 PDF。我这样做是因为注销后,您仍然可以访问该文件。

于 2019-04-16T05:28:26.957 回答
0

您可以使用基于模式的过滤器限制对下载页面的访问

Route::filter('download', function()
{
    //here you check if the user is logged in
    if(!Auth::check()){
        return 'you should be logged in to access the download page';
    }
});

Route::when('download/*', 'download'); 

查看文档以获取更多详细信息

于 2014-04-21T11:01:16.203 回答