How to Get Media URL in Magento 2?

If you're a Magento developer, you certainly know that effective store management often requires programming work. There are lots of tasks you need to perform — from running static content deploy and optimizing Magento 2 reindex to getting current products and media URLs. Some of these are rather time-consuming or even complicated at times.

However, it is much easier if you know the proper methods to use.

In this article, in particular, you'll learn how to get media URLs in Magento 2. 

Get Media URL Using Dependency Injection 

The dependency injection method is among the most common ones when it comes to getting media URLs in Magento.

So, to apply it, go to your phtml block file and create a _construct function:

    public function __construct
(
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
$this->_storeManager = $storeManager;
}

After that you can get a media URL in your phtml file:

$mediaUrl = $this ->_storeManager-> getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
echo $mediaUrl;

Get Media URL Using the Object Manager

One more way to get a media URL is to use the object manager. Just follow the below method:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class); $mediaUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
echo $mediaUrl;

Note: we strongly recommend you avoid the direct usage of the object manager. Though quite simple at first glance, this method hides the real dependencies of the class. 

These are the ways to get media URLs in Magento, so you can go for the one you find the most convenient. After that, you might also need to learn how to get other URLs in Magento 2.