如何确定 Laravel 5.2 的 public 目录中的文件

How to determine file exist in public directory for Laravel 5.2

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

您可以使用存储门面:

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

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

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

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

希望对您有所帮助:)

您可以使用 Laravel 的存储门面作为 El_Matella suggested. However, you could also do this pretty easily with "vanilla" PHP, using PHP's built-in 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 */
}

您可以使用这个小工具来检查目录是否为空。

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

file_exists(public_path($name)

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

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