【问题标题】:How to Check file exists in Laravel如何检查文件是否存在于 Laravel
【发布时间】:2021-10-06 12:27:53
【问题描述】:

我有一个 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)) 函数正在执行!

我想检查目录中的文件,即使目录存在,如果文件不存在,则抛出错误消息,说文件不存在。

【问题讨论】:

    标签: php laravel laravel-7


    【解决方案1】:

    添加一个额外的条件来检查给定的路径是文件而不是目录

    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');
            }
        }
    

    【讨论】:

      【解决方案2】:

      您可以通过验证routename 输入来修复您的代码,使其永远不会为空(并且可能具有特定的文件扩展名?) , 无论如何都很好。

      如果失败,您可以尝试File::isDirectory($dir),它基本上调用is_dir(...)

      请注意,如果您使用 Laravel 的 Storage::disk('public') 功能,它可能会让您对存储解决方案有更多控制权。 API 有点不同,但与它相关的概率范围很广。在此处阅读更多信息:https://laravel.com/docs/8.x/filesystem#introduction

      【讨论】:

        猜你喜欢
        • 2020-06-25
        • 2017-01-02
        • 2019-01-12
        • 2023-03-12
        • 2010-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        相关资源
        最近更新 更多