Alex
Alex

Reputation: 71

How to get all files from folder and subfolder in magento 2

I made a module for uploading images in frontend. Magento 2 saves files in a special way. For example:

How to get all files from [module_folder]?

enter image description here

Upvotes: 5

Views: 6518

Answers (1)

TTech IT Solutions
TTech IT Solutions

Reputation: 179

Try the below, use the directorylist class to get the path, and the file class to read the directory :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;
}

Upvotes: 7

Related Questions