Laravel 5.1 如何检查目录中是否存在文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31973490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:10:06  来源:igfitidea点击:

Laravel 5.1 How to check for the presence a file in a directory?

phplaravelfile-uploadlaravel-5.1

提问by Ali Erfani

I have a form in which users can upload files to the upload folder. In the controller I need to check if the file already exists in the upload directory and if it exists not to allow uploading the same file twice. How can I check this?

我有一个表单,用户可以在其中将文件上传到上传文件夹。在控制器中,我需要检查文件是否已存在于上传目录中,以及是否存在不允许上传同一文件两次。我该如何检查?

回答by dnetix

Maybe the problem it's that you are checking if the file exists in the root folder of the server.

也许问题在于您正在检查该文件是否存在于服务器的根文件夹中。

Try this

尝试这个

    if (file_exists(public_path('uploads/'.$file->getClientOriginalName()))) {
        return redirect()->back()->withInput()->withErrors([' File already exists.']);
    }

回答by gencblakqori

If your files are stored in the "public" folder, then try this :

如果您的文件存储在“public”文件夹中,请尝试以下操作:

\File::exists(public_path().'\uploads\'.$file->getClientOriginalName())

回答by Chamandeep

First you have to mention use Fileat top of the page in your controller

首先,您必须在控制器的页面顶部提及 使用文件

$imagepath = "1.jpg";

$directoryPath = 'user_img/'.$imagepath;

if(File::exists($directoryPath)){
    //echo "n exist"; die();
} else {  echo "not exists";   }