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

时间:2015-07-09 11:47:34

标签: php laravel laravel-5 storage

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

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

8 个答案:

答案 0 :(得分:27)

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

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

    'disks' => [

    'local' => [
        'driver' => 'local',
        'root'   => storage_path().'/app',
    ],

    'public' => [
        'driver' => 'local',
        'root'   => public_path(),
    ],

    's3' => '....'

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

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

$ exists变量会告诉您 public 文件夹中是否存在 file.jpg ,因为存储磁盘' public' 指向项目的公共文件夹。

您可以使用自定义磁盘的文档中的所有会话方法。只需添加磁盘(' public')部分。

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

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

答案 1 :(得分:15)

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

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

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

答案 2 :(得分:9)

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

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

答案 3 :(得分:2)

您可以使用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",
  ]
]

答案 4 :(得分: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']
  }

答案 5 :(得分:0)

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

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

    }
    else {

    }
}

答案 6 :(得分:0)

请使用以下代码,并获取公用文件夹中特定文件夹的所有子目录。单击某些文件夹后,它将列出每个文件夹中的文件。

控制器文件

 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

答案 7 :(得分:0)

您可以获取所有文件:

use Illuminate\Support\Facades\Storage;

..

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