1

我正在使用 spatie 库上传一些文件,这些文件将保存到存储文件夹中。我现在想要完成的是当我是经过身份验证的用户时查看这些文件或图像。我尝试使用此命令创建符号链接,

php artisan storage:link

但这使得这些文件可以公开查看。我只想查看那些文件,只有当用户是经过身份验证的用户时。到目前为止,这就是我所做的,但似乎我错过了一些东西。

路线 :

Route::get('/storage/{filePath}', 'ComplaintsController@fileStorageServe')->where(['filePath' => '.*'])->name('complaints.viewfile');

控制器 :

public function fileStorageServe($file) {
    // know you can have a mapping so you dont keep the sme names as in local (you can not precsise the same structor as the storage, you can do anything)

    // any permission handling or anything else

    // we check for the existing of the file 
    if (!Storage::disk('local')->exists($filePath)){ // note that disk()->exists() expect a relative path, from your disk root path. so in our example we pass directly the path (/.../laravelProject/storage/app) is the default one (referenced with the helper storage_path('app')
        abort('404'); // we redirect to 404 page if it doesn't exist
    } 
    //file exist let serve it 

    // if there is parameters [you can change the files, depending on them. ex serving different content to different regions, or to mobile and desktop ...etc] // repetitive things can be handled through helpers [make helpers]

    return response()->file(storage_path('app'.DIRECTORY_SEPARATOR.($filePath))); // the response()->file() will add the necessary headers in our place (no headers are needed to be provided for images (it's done automatically) expected hearder is of form => ['Content-Type' => 'image/png'];

    // big note here don't use Storage::url() // it's not working correctly.  
}

看法 :

@foreach($complaint->attachments as $attachment)
  <a href="{{url('complaints.viewfile', $attachment->getUrl())}}" target="_blank">{{ $attachment->file_name }}</a>
@endforeach

当我点击链接时,它会给我这样的东西。

http://127.0.0.1:8000/complaints.viewfile/http%3A%2F%2F127.0.0.1%3A8000%2Fstorage%2F3%2F60580fdeadc55_worship.jpg

请帮忙。谢谢...

4

2 回答 2

1

您需要了解 Web 服务器如何提供文件以及它如何与 laravel 应用程序交互。

你可能已经设置了 nginx 或 apache 来从你的 laravel 应用程序的公共文件夹中提供文件。即:/var/www/sites/laravel-site/public

当一个 HTTP 请求被发送到你的服务器时,如果你的 nginx 或 apache 被配置为laravel-site.com/storage/documents/secrets.pdf静态地服务文件,那么你的 laravel 应用程序代码甚至永远不会运行,并且你无法在应用程序级别控制对这些文件的访问。

如果要设置对文件的访问控制,您首先需要确保不会静态处理请求,然后在检查用户/请求是否具有访问文件的权限后设置提供文件的路由(s ) 你想服务。

关于如何做到这一点,还有很多其他很棒的答案资源。

于 2021-03-22T07:49:42.007 回答
-2

如果我错了,请纠正我,但不是通过系统设置做到这一点的最简单方法?就像您有不同的用户一样,您只需将它们放在对文件夹/文件具有不同权限的不同组中。

于 2021-03-22T07:03:28.663 回答