如何确定 Laravel 5.2 的公共目录中存在文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35829488/
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 13:21:15  来源:igfitidea点击:

How to determine file exist in public directory for Laravel 5.2

laravellaravel-5.2

提问by Misterk

I have some image files in public/image directory, so I want to determine if a file exist in that directory before I save a new file. How to determine if a file exist?

我在 public/image 目录中有一些图像文件,所以我想在保存新文件之前确定该目录中是否存在文件。如何判断文件是否存在?

回答by Hammerbot

You can use the Storage Facade:

您可以使用存储外观:

Storage::disk('image')->exists('file.jpg'); // bool

If you are using the disk imageas shown above, you need to define a new disk in your config/filesystems.phpand add the following entry in your disksarray:

如果您使用image如上所示的磁盘,则需要在您的磁盘中定义一个新磁盘config/filesystems.php并在您的disks阵列中添加以下条目:

'image' => [
    'driver' => 'local',
    'root' => storage_path('app/public/image'),
    'visibility' => 'public',
],

Here is the documentation if you want to know more on that Facade: https://laravel.com/docs/5.2/filesystem

如果您想了解有关该 Facade 的更多信息,请参阅以下文档:https: //laravel.com/docs/5.2/filesystem

Hope it helps :)

希望能帮助到你 :)

回答by John Slegers

You could use Laravel's storage Facade as El_Matellasuggested. However, you could also do this pretty easily with "vanilla"PHP, using PHP's built-in is_file()function :

您可以按照El_Matella 的建议使用 Laravel 的存储外观。但是,您也可以使用 PHP 的内置函数使用“vanilla”PHP轻松完成此操作is_file()

if (is_file('/path/to/foo.txt')) {
    /* The path '/path/to/foo.txt' exists and is a file */
} else {
    /* The path '/path/to/foo.txt' does not exist or is not a file */
}

回答by AmirRezaM75

file_exists(public_path($name)

file_exists(public_path($name)

here is my solution to check if file exists before downloading file.

这是我在下载文件之前检查文件是否存在的解决方案。

if (file_exists(public_path($name)))
    return response()->download(public_path($name));

回答by oseintow

You can use this little utility to check if the directory is empty.

您可以使用这个小实用程序来检查目录是否为空。

if($this->is_dir_empty(public_path() ."/image")){ 
   \Log::info("Is empty");
}else{
   \Log::info("It is not empty");
}

public function is_dir_empty($dir) {
  if (!is_readable($dir)) return NULL; 
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
     if ($entry != "." && $entry != "..") {
     return FALSE;
     }
  }
  return TRUE;
}

source

来源