2016-01-19 142 views
0

如何获取Magento2中媒体文件的绝对路径? 我写了一个函数来获取绝对路径,但它不工作。Magento2中的绝对路径

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; 
    } 

回答

7

应用程序/ autoloader.php

包含:

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

有人会做这样的事情:

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

这就是说,通过依赖注入的Magento \框架\文件系统是我的首选方法

2
/* @var \Magento\Framework\ObjectManagerInterface $om/

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

$dir = $om->get('Magento\Framework\Filesystem'); 

$mediadir = $dir->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA); 

$path = $mediadir->create('foldername'); 

试试它的工作对我来说..

-3
$rootDirectory = Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\Filesystem') 
        ->getDirectoryRead(DirectoryList::MEDIA); 
+2

你能解释一下你的答案吗? [来自评论](http://stackoverflow.com/review/low-quality-posts/11855039) –

0

首先,你需要注入DirectoryList类:

public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\App\Filesystem\DirectoryList $directoryList, array $data = []) { 
     parent::__construct($context, $data); 
     $this->directory_list = $directoryList; 
    } 

之后,你将使用检索DirectoryList方法不同的路径,如:

对于根文件夹

$this->directoryList->getRoot(); 

对于媒体文件夹

$this->directory_list->getPath('media'); 

其他文件夹

// Get app folder 
$this->directory_list->getPath('app'); 

// Get etc Folder 
$this->directory_list->getPath('etc'); 

// Get public folder 
$this->directory_list->getPath('pub'); 

// Get var folder 
$this->directory_list->getPath('var'); 
0

您可以使用此:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$fileSystem = $om->get('Magento\Framework\Filesystem'); 
$mediaDirectory = $fileSystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA); 
2

你可以用它来获得在Magento 2媒体和基本绝对路径,如:

$storeManager = $_objectMedia->get('Magento\Store\Model\StoreManagerInterface'); 
$currentStore = $storeManager->getStore(); 

$mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); 

$_baseurl = $storeManager->getStore()->getBaseUrl(); 

试试吧,对我来说工作很好....

+1

右....... code –