在Laravel 5中,如何获取公用文件夹中所有文件的列表?

问题描述 投票:17回答:5

我想自动生成我公共文件夹中所有图像的列表,但我似乎无法找到任何可以帮助我做到这一点的对象。

Storage类似乎是这项工作的一个很好的候选者,但它只允许我搜索存储文件夹中的文件,该文件夹位于公共文件夹之外。

php laravel laravel-5 storage
5个回答
27
投票

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

在disks阵列的config / filesystems.php中添加所需的文件夹。这种情况下的公用文件夹。

    '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')-> // any method you want from 

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


15
投票

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

要么

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

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


9
投票

考虑使用glob。无需在Laravel 5中使用帮助程序类/方法使准系统PHP过度复杂化。

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

0
投票

要列出公共目录中的所有图像,请尝试以下方法:请参阅此处btw 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']
  }

0
投票

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

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

    }
    else {

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.