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

1

5

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

  • uploading file - file.png,
  • path to file - pub/media/[module_folder]/f/i/file.png.

How to get all files from [module_folder]?

enter image description here

Cyclograph answered 16/2, 2016 at 9:52 Comment(2)
Get them how? In what system/language? In what format?Lining
I want to get names and paths of all file in folder and subfolder. Magento 2, PHPCyclograph
W
7

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;
}
Wedding answered 14/7, 2020 at 23:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.