【发布时间】:2016-06-20 03:53:17
【问题描述】:
我在 public/image 目录中有一些图像文件,所以我想在保存新文件之前确定该目录中是否存在文件。 如何判断文件是否存在?
【问题讨论】:
标签: laravel laravel-5.2
我在 public/image 目录中有一些图像文件,所以我想在保存新文件之前确定该目录中是否存在文件。 如何判断文件是否存在?
【问题讨论】:
标签: laravel laravel-5.2
您可以按照El_Matella 的建议使用 Laravel 的存储外观。但是,您也可以使用 PHP 的内置 is_file() 函数,通过"vanilla" 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 */
}
【讨论】:
file_exists(public_path($name)
这是我在下载文件之前检查文件是否存在的解决方案。
if (file_exists(public_path($name)))
return response()->download(public_path($name));
【讨论】:
您可以使用这个小工具来检查目录是否为空。
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;
}
【讨论】:
您可以使用存储门面:
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
希望对你有帮助:)
【讨论】: