如何从magento 2中的文件夹和子文件夹中获取所有文件

Ale*_*lex 5 filesystems getfiles magento2

我制作了一个用于在前端上传图像的模块。Magento 2 以一种特殊的方式保存文件。例如:

  • 上传文件- file.png,
  • 文件路径- pub/media/[module_folder]/f/i/file.png.

如何获取所有文件[module_folder]

在此输入图像描述

小智 7

尝试下面的方法,使用目录列表类来获取路径,使用文件类来读取目录:D

public  function __construct(
    \Magento\Framework\Filesystem\DirectoryList $directoryList,
    \Magento\Framework\Filesystem\Driver\File $driverFile,
    LoggerInterface $logger)
{
    $this->directoryList =$directoryList;
    $this->driverFile = $driverFile;
    $this->logger = $logger;
}

public function getAllFiles($path = '/import/') {
    $paths = [];
    try {
        //get the base folder path you want to scan (replace var with pub / media or any other core folder)
        $path = $this->directoryList->getPath('var') . $path;
        //read just that single directory
        $paths =  $this->driverFile->readDirectory($path);
        //read all folders
        $paths =  $this->driverFile->readDirectoryRecursively($path);
    } catch (FileSystemException $e) {
        $this->logger->error($e->getMessage());
    }

    return $paths;
}
Run Code Online (Sandbox Code Playgroud)