How to get media path in Magento 2.1. I tried lots of option but it is not working?
I want to display the image in front-end inside .phtml file.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityyou can get media path by $object method
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
echo $objectManager->get('Magento\Store\Model\StoreManagerInterface')
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
factories method
<?php
namespace Namespace\Modulename\Block;
use Magento\Framework\ObjectManagerInterface;
class Banners extends Template
{
protected $objectManager;
public function __construct(
.......
ObjectManagerInterface $objectManager
...) {
...........
$this->objectManager = $objectManager;
...............
}
public function getMediaUrl(){
$media_dir = $this->objectManager->get('Magento\Store\Model\StoreManagerInterface')
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
return $media_dir;
}
}
........
?>
in phtml file
<?php echo $block->getMediaUrl(); ?>
Usage of Object Manager is discouraged as per Magento's coding standards. In a template file, we can get the media URL using the following code:
$this->helper('\Magento\Cms\Helper\Wysiwyg\Images')->getBaseUrl()
As per the Magento's recommendation, the document root of your website should be outside pub
directory during development and it should be inside pub
directory when moved to production.
Hence we cannot hard code the pub
directory while getting media URL in the template files. The above code will give you the correct media URL irrespective of your document root location.
Get media path by objectManager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
echo $objectManager->get('Magento\Store\Model\StoreManagerInterface')
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
Get media path by Dependency Injection
protected $_storeManager;
public function __construct(
...
\Magento\Store\Model\StoreManagerInterface $storeManager,
...
) {
...
$this->_storeManager = $storeManager;
...
}
public function getMediaUrl()
{
$mediaUrl = $this->_storeManager
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
return $mediaUrl;
}
Now call function getMediaUrl()
in phtml
<?php echo $block->getMediaUrl(); ?>
$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
Please check this code. It will give you media path.