在以前的项目中,我通过以下方式保护了上传内容:
创建了存储磁盘:
config/filesystems.php
'myDisk' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'private',
],
这将上传文件到\storage\app\uploads\
,这个路径不对公众开放。
在您的控制器中保存文件:
Storage::disk('myDisk')->put('/ANY FOLDER NAME/' . $file, $data);
为了让用户查看文件并保护上传内容免受未授权访问,首先要检查磁盘上的文件是否存在:
public function returnFile($file)
{
$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)
{
if (strpos($file, '.') !== false) {
if (Auth::user()->hasAnyRole(['Admin'])) {
return $this->returnFile($file);
} else {
return $this->returnFile($file);
}
} else {
return redirect()->route('home');
}
}
最后在 Web.php 路由文件中:
Route::get('uploads/user-files/{filename}', 'MiscController@licenceFileShow');