如何检查 Laravel 中是否存在文件
How to Check file exists in Laravel
我有一个 Laravel 控制器函数 file_fetch()
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
如果我检查文件 public/folder/app/index.html
并且检查 public/newfolder
(新文件夹不存在),这会起作用,因此它会执行 else
函数并重定向并显示错误消息,但是如果我搜索 public/folder/app/
我没有指定文件名,但目录存在,因此正在执行 if(!File::exists($destinationPath))
函数!
我只想检查目录中的文件,即使目录存在,如果文件不存在,抛出一条错误消息,说文件不存在。
再添加一个附加条件来检查给定路径是文件而不是目录
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath) && !is_dir($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
您可能可以通过验证 routename
输入来修复您的代码,使其永远不会为空(并且可能具有特定的文件扩展名?)
, 无论如何都很好。
如果失败,您可以尝试 File::isDirectory($dir)
,它基本上调用 is_dir(...)
。
请注意,如果您使用 Laravel 中的 Storage::disk('public')
功能,您可能会更好地控制存储解决方案。 API 有点不同,但与之相关的概率范围很广。在这里阅读更多相关信息:https://laravel.com/docs/8.x/filesystem#introduction.
我有一个 Laravel 控制器函数 file_fetch()
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
如果我检查文件 public/folder/app/index.html
并且检查 public/newfolder
(新文件夹不存在),这会起作用,因此它会执行 else
函数并重定向并显示错误消息,但是如果我搜索 public/folder/app/
我没有指定文件名,但目录存在,因此正在执行 if(!File::exists($destinationPath))
函数!
我只想检查目录中的文件,即使目录存在,如果文件不存在,抛出一条错误消息,说文件不存在。
再添加一个附加条件来检查给定路径是文件而不是目录
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath) && !is_dir($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
您可能可以通过验证 routename
输入来修复您的代码,使其永远不会为空(并且可能具有特定的文件扩展名?)
, 无论如何都很好。
如果失败,您可以尝试 File::isDirectory($dir)
,它基本上调用 is_dir(...)
。
请注意,如果您使用 Laravel 中的 Storage::disk('public')
功能,您可能会更好地控制存储解决方案。 API 有点不同,但与之相关的概率范围很广。在这里阅读更多相关信息:https://laravel.com/docs/8.x/filesystem#introduction.