【问题标题】:How to determine file exist in public directory for Laravel 5.2如何确定 Laravel 5.2 的公共目录中是否存在文件
【发布时间】:2016-06-20 03:53:17
【问题描述】:

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

【问题讨论】:

    标签: laravel laravel-5.2


    【解决方案1】:

    您可以按照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 */
    }
    

    【讨论】:

      【解决方案2】:

      file_exists(public_path($name)

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

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

      【讨论】:

        【解决方案3】:

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

        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

        【讨论】:

          【解决方案4】:

          您可以使用存储门面:

          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

          希望对你有帮助:)

          【讨论】:

            猜你喜欢
            • 2017-01-02
            • 2021-12-14
            • 2016-06-05
            • 2011-05-25
            • 2022-11-24
            • 2016-07-03
            • 1970-01-01
            • 1970-01-01
            • 2015-10-17
            相关资源
            最近更新 更多