首页 > 解决方案 > Laravel 使用 File 方法从文件夹中获取文件名

问题描述

无法弄清楚如何file name从````filePath```中的文件夹中获取

use Illuminate\Support\Facades\File;

    $filePath = storage_path('app/apiFiles/'.auth()->user()->id_message.'/');

    $fileName = File::files($filePath);

    dd($fileName);

dd($fileName)返回数组但我只需要filename可以从数组中分离出来吗?

我需要从数组中得到的只是这个filename: "Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"

 array:1 [▼
    0 => Symfony\Component\Finder\SplFileInfo {#293 ▼
    -relativePath: ""
    -relativePathname: "Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
    path: "/var/www/html/domain/storage/app/apiFiles/910960"
    filename: "Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
    basename: "Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
    pathname: "/var/www/html/domain/storage/app/apiFiles/910960/Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
    extension: "zip"
    realPath: "/var/www/html/domain/storage/app/apiFiles/910960/Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"
   aTime: 2020-10-22 06:46:37
   mTime: 2020-10-22 06:46:37
   cTime: 2020-10-22 06:46:37
   inode: 1308192
   size: 3180822
   perms: 0100644
   owner: 33
   group: 33
   type: "file"
   writable: true
   readable: true
   executable: false
   file: true
   dir: false
   link: false
 }

]

标签: phpfilelaravel-5filenames

解决方案


解决方案,很奇怪,但对我的项目来说已经足够了

 $filePath = storage_path('app/Files/'.auth()->user()->id_message.'/');

dd($filePath)返回->/var/www/html/domain/storage/app/apiFiles/910960/

目录910960中只有一个文件hash.zip

从目录中获取文件名:

$fileNameArray = preg_grep("~\.(zip)$~", scandir($filePath));

dd($fileNameArray)返回 -> 数组"Z1iZ03gEhltPZj2Z2Rxnnuga2eXywheL4pQc5q0I.zip"

最后一步是将数组转换为字符串:

$fileNameString = implode("", $fileNameArray);

推荐阅读