【问题标题】:In Laravel, how can I obtain a list of all files in a public folder?在 Laravel 中,如何获取公用文件夹中所有文件的列表?
【发布时间】:2015-09-27 18:32:57
【问题描述】:

我想自动生成公用文件夹中所有图像的列表,但我似乎找不到任何可以帮助我执行此操作的对象。

Storage 类似乎是该工作的理想人选,但它只允许我搜索存储文件夹中的文件,该文件夹位于公用文件夹之外。

【问题讨论】:

    标签: php laravel storage


    【解决方案1】:

    您可以为 Storage 类创建另一个磁盘。在我看来,这将是您的最佳解决方案。

    在磁盘阵列的 config/filesystems.php 中添加您想要的文件夹。本例中的 public 文件夹。

        'disks' => [
    
        'local' => [
            'driver' => 'local',
            'root'   => storage_path().'/app',
        ],
    
        'public' => [
            'driver' => 'local',
            'root'   => public_path(),
        ],
    
        's3' => '....'
    

    然后您可以通过以下方式使用 Storage 类在您的公用文件夹中工作:

    $exists = Storage::disk('public')->exists('file.jpg');
    

    $exists 变量会告诉您 file.jpg 是否存在于 public 文件夹中,因为 Storage disk 'public' 指向 public项目文件夹。

    您可以将文档中的所有 Storage 方法与您的自定义磁盘一起使用。只需添加 disk('public') 部分。

     Storage::disk('public')-> // any method you want from 
    

    http://laravel.com/docs/5.0/filesystem#basic-usage

    稍后编辑:

    人们抱怨我的回答没有给出列出文件的确切方法,但我的意图是永远不会删除操作复制/粘贴到他的项目中的一行代码。我想“教”他,如果我可以使用这个词,如何使用 laravel 存储,而不是仅仅粘贴一些代码。

    无论如何,列出文件的实际方法是:

    $files = Storage::disk('public')->files($directory);
    
    // Recursive...
    $files = Storage::disk('public')->allFiles($directory);
    

    配置部分和背景都在上面,在我原来的回答中。

    【讨论】:

    • 奖励更多“laravelish”解决方案
    • 这是一个冗长的答案,有 20 个赞。但是,您没有回答“我的公共文件夹中所有图像的列表”的问题,并且 laravel 文档 apge 并没有真正解释 Storage::allFiles() 返回的内容。是的,一个数组,但是数组里面是什么?如何从中获取文件名和路径?
    • 我的想法也是。他们没有回答问题。
    • 我不明白问题的作者是如何接受这个答案的。
    • storage_path('app') 为你做斜线
    【解决方案2】:

    Storage::disk('local')->files('optional_dir_name');

    或者只是某种类型的文件

    array_filter(Storage::disk('local')->files(), function ($item) {
       //only png's
       return strpos($item, '.png');
    });
    

    请注意,laravel 磁盘有 files()allfiles()allfiles 是递归的。

    【讨论】:

    • 谢谢!我创建了一个符号链接,因此我可以通过资产('storage/imgagName.jpg')访问照片,然后通过 Storage::disk('local')->files() 访问照片以在我的视图中的表格中显示它们。
    • !警告:这仍然是提取每个文件并遍历每个文件
    • @Peter ya... 那是 array_filter(...) 你有什么建议?
    【解决方案3】:

    考虑使用glob。无需使用 Laravel 5 中的辅助类/方法使准系统 PHP 过于复杂。

    <?php
    foreach (glob("/location/for/public/images/*.png") as $filename) {
        echo "$filename size " . filesize($filename) . "\n";
    }
    ?>
    

    【讨论】:

    • 对于本地文件系统来说似乎是最有效的
    【解决方案4】:

    要列出目录中的所有文件,请使用此

      $dir_path = public_path() . '/dirname';
       $dir = new DirectoryIterator($dir_path);
      foreach ($dir as $fileinfo) {
        if (!$fileinfo->isDot()) {
    
        }
        else {
    
        }
    }
    

    【讨论】:

    • isFile 在这里可能很有用。对我来说更容易理解
    【解决方案5】:

    您可以使用FilesystemReader::listContents

    Storage::disk('public')->listContents();
    

    示例响应...

    [
      [
        "type" => "file",
        "path" => ".gitignore",
        "timestamp" => 1600098847,
        "size" => 27,
        "dirname" => "",
        "basename" => ".gitignore",
        "extension" => "gitignore",
        "filename" => "",
      ],
      [
        "type" => "dir",
        "path" => "avatars",
        "timestamp" => 1600187489,
        "dirname" => "",
        "basename" => "avatars",
        "filename" => "avatars",
      ]
    ]
    

    【讨论】:

    • 完美解决方案
    【解决方案6】:

    要列出公共目录中的所有图像,请尝试以下操作: 顺便说一句http://php.net/manual/en/class.splfileinfo.php

      function getImageRelativePathsWfilenames(){
    
          $result = [];
    
        $dirs = File::directories(public_path());
    
        foreach($dirs as $dir){
          var_dump($dir); //actually string: /home/mylinuxiser/myproject/public"
          $files = File::files($dir);
          foreach($files as $f){
            var_dump($f); //actually object SplFileInfo
            //object(Symfony\Component\Finder\SplFileInfo)#628 (4) {
            //["relativePath":"Symfony\Component\Finder\SplFileInfo":private]=>
            //string(0) ""
            //["relativePathname":"Symfony\Component\Finder\SplFileInfo":private]=>
            //string(14) "text1_logo.png"
            //["pathName":"SplFileInfo":private]=>
            //string(82) "/home/mylinuxiser/myproject/public/img/text1_logo.png"
            //["fileName":"SplFileInfo":private]=>
            //string(14) "text1_logo.png"
            //}
    
            if(ends_with($f, ['.png', '.jpg', '.jpeg', '.gif'])){
              $result[] = $f->getRelativePathname(); //prefix your public folder here if you want
            }
          }
        }
        return $result; //will be in this case ['img/text1_logo.png']
      }
    

    【讨论】:

    • 如何将其转换为 laravel 图像对象
    【解决方案7】:

    请使用以下代码获取公用文件夹中特定文件夹的所有子目录。当一些人点击文件夹时,它会列出每个文件夹中的文件。

    控制器文件

     public function index() {
    
        try {
    
            $dirNames = array();  
            $this->folderPath = 'export'.DS.str_replace( '.', '_', $this->getCurrentShop->getCurrentShop()->shopify_domain ).DS.'exported_files';
            $getAllDirs = File::directories( public_path( $this->folderPath ) );
    
            foreach( $getAllDirs as $dir ) {
    
                $dirNames[] = basename($dir);
    
            }
            return view('backups/listfolders', compact('dirNames'));
    
        } catch ( Exception $ex ) {
            Log::error( $ex->getMessage() );
        }
    
    
    
    }
    
    public function getFiles( $directoryName ) {
    
        try {
            $filesArr = array();
            $this->folderPath = 'export'.DS.str_replace( '.', '_', $this->getCurrentShop->getCurrentShop()->shopify_domain ).DS.'exported_files'. DS . $directoryName;
            $folderPth = public_path( $this->folderPath );
            $files = File::allFiles( $folderPth ); 
            $replaceDocPath = str_replace( public_path(),'',$this->folderPath );
    
            foreach( $files as $file ) {
    
                $filesArr[] = array( 'fileName' => $file->getRelativePathname(), 'fileUrl' => url($replaceDocPath.DS.$file->getRelativePathname()) );
    
            }
    
            return view('backups/listfiles', compact('filesArr'));
    
        } catch (Exception $ex) {
            Log::error( $ex->getMessage() );
        }
    
    
    }
    

    路由(Web.php)

    Route::resource('displaybackups', 'Displaybackups\BackupController')->only([ 'index', 'show']);
    

    Route::get('get-files/{directoryName}', 'Displaybackups\BackupController@getFiles');

    查看文件 - 列出文件夹

    @foreach( $dirNames as $dirName)
        <div class="col-lg-3 col-md-3 col-sm-4 align-center">
            <a href="get-files/{{$dirName}}" class="btn btn-light folder-wrap" role="button">
                <span class="glyphicon glyphicon-folder-open folderIcons"></span>
                {{ $dirName }}
            </a>
        </div>
    @endforeach
    

    查看 - 列出文件

    @foreach( $filesArr as $fileArr)
        <div class="col-lg-2 col-md-3 col-sm-4">
            <a href="{{ $fileArr['fileUrl'] }}" class="waves-effect waves-light btn green folder-wrap">
                <span class="glyphicon glyphicon-file folderIcons"></span>
                <span class="file-name">{{ $fileArr['fileName'] }}</span>
            </a>
        </div>
    @endforeach
    

    【讨论】:

      【解决方案8】:

      你可以得到所有的文件:

      use Illuminate\Support\Facades\Storage;
      

      ..

      $files = Storage::disk('local')->allFiles('public');
      

      【讨论】:

        【解决方案9】:

        用于获取公共路径的用户文件命名空间。然后使用此代码从所选目录中获取所有文件

        use File;    
        
          
        

        例如公共目录名称是“媒体”

        $path = public_path('media');
        $filesInFolder = File::allFiles($path);
        
        
        foreach($filesInFolder as $key => $path){
          $files = pathinfo($path);
          $allMedia[] = $files['basename'];
        }
        

        【讨论】:

        • 请考虑在您的代码中添加解释。
        • 没有任何解释的代码很少有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请编辑您的问题并解释它如何回答所提出的具体问题。见How to Answer
        猜你喜欢
        • 2013-11-26
        • 1970-01-01
        • 2011-12-10
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-17
        • 2021-11-06
        相关资源
        最近更新 更多