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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31316543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:22:11  来源:igfitidea点击:

In Laravel, how can I obtain a list of all files in a public folder?

phplaravelstorage

提问by kant312

I'd like to automatically generate a list of all images in my public folder, but I cannot seem to find any object that could help me do this.

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

The Storageclass seems like a good candidate for the job, but it only allows me to search files within the storage folder, which is outside the public folder.

Storage级似乎是一个很好的候选人做这份工作,但只允许我存储文件夹,这是外面的公共文件夹中搜索文件。

回答by igs013

You could create another disk for Storage class. This would be the best solution for you in my opinion.

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

In config/filesystems.phpin the disks array add your desired folder. The publicfolder in this case.

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

    'disks' => [

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

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

    's3' => '....'

Then you can use Storageclass to work within your public folder in the following way:

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

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

The $exists variable will tell you if file.jpgexists inside the publicfolder because the Storage disk 'public'points to public folder of project.

$exists 变量会告诉你file.jpg 是否存在于public文件夹中,因为存储磁盘“public”指向项目的 public 文件夹。

You can use all the Sessionmethods from documentation, with your custom disk. Just add the disk('public') part.

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

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

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

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

回答by Tarek Adam

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

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

or

或者

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

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

Note that laravel disk has files()and allfiles(). allfilesis recursive.

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

回答by drmarvelous

Consider using glob. No need to overcomplicate barebones PHP with helper classes/methods in Laravel 5.

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

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

回答by Adnan Rasheed

To list all files in directory use this

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

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

    }
    else {

    }
}

回答by Toskan

To list all images in your public dir try this: see here btw http://php.net/manual/en/class.splfileinfo.php

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

回答by Liz Eipe C

Please use the following code and get all the subdirectories of a particular folder in the public folder. When some click the folder it lists the files inside each folder.

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

Controller File

控制器文件

 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() );
    }


}

Route ( Web.php )

路线 ( Web.php )

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

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

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

View files - List Folders

查看文件 - 列出文件夹

@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

View - List Files

查看 - 列出文件

@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