在以前的项目中,我通过执行以下操作来保护上传:
创建的存储磁盘:
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)
{
//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');