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

时间:2016-03-06 16:39:35

标签: laravel laravel-5.2

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

4 个答案:

答案 0 :(得分:3)

您可以使用存储外观:

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

希望有所帮助:)

答案 1 :(得分:2)

您可以使用Laravel的存储Facade作为El_Matella建议。但是,您也可以使用PHP的内置"vanilla"函数轻松地使用is_file() PHP执行此操作:

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 */
}

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

file_exists(public_path($name)

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

if (file_exists(public_path($name)))
    return response()->download(public_path($name));
相关问题