我想自动生成我公共文件夹中所有图像的列表,但我似乎无法找到任何可以帮助我做到这一点的对象。
Storage
类似乎是这项工作的一个很好的候选者,但它只允许我搜索存储文件夹中的文件,该文件夹位于公共文件夹之外。
您可以为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
Storage::disk('local')->files('optional_dir_name');
要么
array_filter(Storage::disk('local')->files(), function ($item) {return strpos($item, 'png');});
请注意,laravel磁盘有files()
和allfiles()
。 allfiles
是递归的。
考虑使用glob。无需在Laravel 5中使用帮助程序类/方法使准系统PHP过度复杂化。
<?php
foreach (glob("/location/for/public/images/*.png") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
要列出公共目录中的所有图像,请尝试以下方法:请参阅此处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']
}
要列出目录中的所有文件,请使用此项
$dir_path = public_path() . '/dirname';
$dir = new DirectoryIterator($dir_path);
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
}
else {
}
}