如何保存一个图像在Laravel的私有目录,然后给予它在浏览器中显示?

bqucvtff  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(40)

我想将图像保存到一个特殊的目录,例如- storage/private_files并在授权后向某些用户显示某些图像。然后用户的图像将不得不显示在浏览器的IMG标签中。文件的路径将与用户一起存储在数据库中。如何在Laravel 8.83.21中正确组织保存和提供图像?

t1qtbnec

t1qtbnec1#

有很多方法可以做到这一点(中间件、策略、user_permissions等)。
我的建议是 (我不知道你的模型调用了什么,也不知道你的代码的结构,但是当你有了这个想法,就把它应用到你的代码中去吧)

  • config/filesystems.php中添加新磁盘
'disks' => [
    'private' => [
        'driver' => 'local',
        'root' => storage_path('app/private_files'),
        'visibility' => 'private',
        'throw' => true,
    ],
],

字符串

  • 要保存文件,请执行以下操作:

$file->storeAs("uploads", "image_x.jpg", "private");或使用Storage Facade

  • 如果文件可供特定用户下载(使用策略)

使用策略的示例

class FilePolicy
{
    public function download(User $user, FileModel $file): bool
    {
        return $user->isAdmin();
        //OR
        return $user->hasAccessTo($file); // assuming you have that function  

    }

    public function show(User $user, FileModel $file): bool
    {
        return $user->isAdmin();
        //OR
        return $user->hasAccessTo($file); // assuming you have that function  

    }
}
// XController.php

public function download(FileModel $file): void
 {
    if ($request->user()->cannot('download', FileModel)) {
        abort(403);
    }

    return Storage::response($file->filename);
}

的数据

  • 在你看来刀锋
@can('show', $file) // similar for download
    <!-- The current user can see the file... -->
@endcan

ni65a41a

ni65a41a2#

您可以考虑使用临时url函数。如果用户有访问权限,您可以为他创建一个临时url并给予用户访问权限。由于临时url已过期,因此无法与其他用户共享url。这是处理文件权限的最佳方法:

$url = Storage::temporaryUrl(
    'file.jpg', now()->addMinutes(5)
);

字符串

相关问题