¿Cómo obtener la ruta del directorio de medios en un archivo phtml en magento 2?


14

Usó el siguiente método para obtener la ruta del directorio de medios , pero devuelve un error.

$om = \Magento\Core\Model\ObjectManager::getInstance();

$directoryList = $om->get(\Magento\App\Filesystem\DirectoryList::class);

$pubMediaDir = $directoryList->getPath(\Magento\App\Filesystem\DirectoryList::MEDIA);

Por favor, ayúdame a encontrar una solución.


1
Tu pregunta no está clara para mí. ¿Puedes explicar más detalles? Además, podemos echar un vistazo: magento.stackexchange.com/a/155238/33057
Khoa TruongDinh

Respuestas:


23

En lugar de usar directo object manager, úsalo como

use Magento\Framework\App\Filesystem\DirectoryList;

protected $_filesystem;

public function __construct(
    \Magento\Framework\Filesystem $filesystem
)
{
    $this->_filesystem = $filesystem;
}

Ahora puedes hacer una ruta de medios,

$mediapath = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();

EDITAR

Si desea usar un Administrador de objetos , puede usar esto (no recomendado)

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

$fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
$mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
echo $mediaPath;
exit;

devuelve un error como este "Error de tipo no capturado: el argumento 2 pasado al espacio de nombres \ Módulo \ Controlador \ Índice \ Cargar :: __ construct () debe ser una instancia de Magento \ Framework \ Filesystem, ninguno proporcionado"
Rita Jose

sí, intente di: compilar e intente de nuevo :)
Keyur Shah

di: compilación realizada, pero de nuevo devuelve un error :( "Error recuperable: el objeto de la clase Magento \ Framework \ Filesystem \ Directory \ Read no se pudo convertir en cadena en / opt / lampp / htdocs / magento214 / app / code / namespace /Customtab/Controller/Index/Upload.php en la línea 18 "
Rita Jose

mira mi edición, si quieres usar el administrador de objetos directo @RitaJose
Keyur Shah

wow: D .. Muchas gracias .. El editado funciona bien :)
Rita Jose

7

Primero deberá inyectar la clase DirectoryList en su constructor de Magento 2:

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

Después de eso, tendrá acceso a los métodos de DirectoryList para recuperar varias rutas. Por ejemplo, para obtener una carpeta multimedia, puede usar:

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

Otros usos posibles son:

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

/* Get configuration folder */
$this->directory_list->getPath('etc');

/* Get libraries or third-party components folder */
$this->directory_list->getPath('lib_internal');

/* Get libraries/components that need to be accessible publicly through web-server folder */
$this->directory_list->getPath('lib_web');

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

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

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

/* Get temporary files folder */
$this->directory_list->getPath('tmp');

/* Get file system caching directory (if file system caching is used) */
$this->directory_list->getPath('cache');

/* Get logs of system messages and errors */
$this->directory_list->getPath('log');

/* Get file system session directory (if file system session storage is used) */
$this->directory_list->getPath('session');

/* Get directory for Setup application*/
$this->directory_list->getPath('setup');

/* Get Dependency injection related file directory */
$this->directory_list->getPath('di');

/* Relative directory key for generated code*/
$this->directory_list->getPath('generation');

/* Temporary directory for uploading files by end-user */
$this->directory_list->getPath('upload');

/* Directory to store composer related files (config, cache etc.) in case if composer runs by Magento Application */
$this->directory_list->getPath('composer_home');

/* A suffix for temporary materialization directory where pre-processed files will be written (if necessary) */
$this->directory_list->getPath('view_preprocessed');

/* Get template minification dir */
$this->directory_list->getPath('html');

devuelve la URL del navegador de los medios ... necesito la ruta de la carpeta de los medios
Rita Jose

Por favor vea mi respuesta actualizada.
Mohit Kumar Arora

hasta que no funcione
Sarfaraj Sipai

Gracias @MohitKumarArora, me salvó el día. la solución anterior funcionó a las mil
maravillas

6

Use el siguiente código para obtener la ruta de medios en el archivo .phtml.

$this->getUrl('pub/media');

Por Objectmanager

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

2
Devuelve la ruta de la URL del navegador. Necesito la ruta de la carpeta de medios
Rita Jose

6

Intenta obtenerlo usando StoreManagerInterface

use Magento\Store\Model\StoreManagerInterface;
protected $storeManager;

public function __construct(
    StoreManagerInterface $storeManager,
)
{
    $this->storeManager = $storeManager;
}

Ahora obtenga la URL de los medios usando

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

no funciona .....
Sarfaraj Sipai
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.