Magento2 Error – What is Base Dir for File in Magento 2

errormagento2

I use following code,

public function execute()
{
    //do your custom stuff here
    $fileName = 'file name for download here';
    $this->fileFactory->create(
        $fileName,
        null, //content here. it can be null and set later 
        base dir of the file to download here
        'application/octet-stream', //content type here
        content lenght here...can be null
    );
 }

What would be the base dir for this file?

/magento/pub/media/downloadable/files/links/l/e/learn-magento.jpg

Best Answer

For Getting Base url For Directory you can follow this.

    protected $_filesystem;

    public function __construct(
        \Magento\Framework\Filesystem $filesystem,
        Action\Context $context
    ){
        $this->_filesystem = $filesystem;
        parent::__construct($context);
    }

    public function getBaseDir() {
        $path = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('your_path');
        return $path;
    }

Pass Your Directory in getAbsolutePath('Here')