Magento 2 Media Directory – How to Get Media Directory Path in PHTML File

controllersdirectorymagento2mediapaths

Used the below method in order to get the media directory path, but it returns an error.

$om = \Magento\Core\Model\ObjectManager::getInstance();

$directoryList = $om->get(\Magento\App\Filesystem\DirectoryList::class);

$pubMediaDir = $directoryList->getPath(\Magento\App\Filesystem\DirectoryList::MEDIA);

Please help me to find a solution.

Best Answer

Instead of using direct object manager, use It like

use Magento\Framework\App\Filesystem\DirectoryList;

protected $_filesystem;

public function __construct(
    \Magento\Framework\Filesystem $filesystem
)
{
    $this->_filesystem = $filesystem;
}

Now you can media path by,

$mediapath = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();

EDIT

If you want to use an Object Manager, then you can use this (not recommended)

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
$mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
echo $mediaPath;
exit;
Related Topic