Search code examples
pathmediaabsolutemagento2

Absolute path in Magento2


How can I get the absolute path of a media file in Magento2? I write a function to get the absolute path, but it is not working.

public function getAbsolutePath()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        /** @var \Magento\Framework\Filesystem $filesystem */
        $filesystem = $objectManager->get('Magento\Framework\Filesystem');
        /** @var \Magento\Framework\Filesystem\Directory\WriteInterface $mediaDirectory */
        $mediaDirectory = $filesystem->getDirectoryWrite(Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
        $mediaPath = $mediaDirectory->getAbsolutePath();
        return $mediaPath;
    }

Solution

  • app/autoloader.php

    contains:

    /**
     * Shortcut constant for the root directory
     */
    define('BP', dirname(__DIR__));
    

    One could do something like:

    $mediaPath = BP.'/pub/media/';
    

    That said, Magento\Framework\Filesystem via dependency injection is my preferred method