我已经安装了 Laravel 5.0 并进行了身份验证。一切正常。
我的网站只对经过身份验证的成员(member)开放。内部的内容仅对经过身份验证的成员提供保护,但站点内部的图像不 protected 以供公众查看。
任何人直接写入图片 URL 都可以看到图片,即使该人没有登录系统。
http://www.somedomainname.net/images/users/userImage.jpg
我的问题:是否可以保护图像(上面的 URL 示例)不被公众查看,换句话说,如果图像的 URL 发送给任何人,则个人必须是成员(member)并登录才能看到图像。
这可能吗?怎么做?
最佳答案
在以前的项目中,我通过执行以下操作来保护上传:
已创建 存储盘 :
config/filesystems.php
'myDisk' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'private',
],
这会将文件上传到
\storage\app\uploads\
不可用公众 观看。要在 Controller 上保存文件:
Storage::disk('myDisk')->put('/ANY FOLDER NAME/' . $file, $data);
为了让用户查看文件并保护上传内容免受 未经授权的使用权。首先检查文件存在在磁盘上:
public function returnFile($file)
{
//This method will look for the file and get it from drive
$path = storage_path('app/uploads/ANY FOLDER NAME/' . $file);
try {
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
} catch (FileNotFoundException $exception) {
abort(404);
}
}
服务如果用户具有正确的访问权限,则该文件:
public function licenceFileShow($file)
{
/**
*Make sure the @param $file has a dot
* Then check if the user has Admin Role. If true serve else
*/
if (strpos($file, '.') !== false) {
if (Auth::user()->hasAnyRole(['Admin'])) {
/** Serve the file for the Admin*/
return $this->returnFile($file);
} else {
/**Logic to check if the request is from file owner**/
return $this->returnFile($file);
}
} else {
//Invalid file name given
return redirect()->route('home');
}
}
最后在 Web.php 路线:
Route::get('uploads/user-files/{filename}', 'MiscController@licenceFileShow');
关于laravel - 如何在 Laravel 5 中保护图像不被公众看到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682421/