Magento – Magento:2 How tomage upload in custom module

admincollection;magento-2.1magento2module

Image upload working fine in tmp folder, then store in DB. I want to after saving data image stored in the base folder pub/media/events
enter image description here

var_dump($data);

" ["events_url"]=> array(1) { [0]=> array(10) { ["name"]=> string(39) "Screenshot_from_2018-04-30_18-07-01.png" ["type"]=> string(9) "image/png" ["tmp_name"]=> string(14) "/tmp/phpGvtNFv" ["error"]=> string(1) "0" ["size"]=> string(6) "744010" ["path"]=> string(45) "/var/www/html/magento8/pub/media/faq/tmp/icon" ["file"]=> string(39) "Screenshot_from_2018-04-30_18-07-01.png" ["url"]=> string(88) "http://127.0.0.1/magento8/pub/media/faq/tmp/icon/Screenshot_from_2018-04-30_18-07-01.png" ["cookie"]=> array(5) { ["name"]=> string(5) "admin" ["value"]=> string(26) "tcq6loa96ki11qfiri6j2llua5" ["lifetime"]=> string(3) "900" ["path"]=> string(15) "/magento8/admin" ["domain"]=> string(9) "127.0.0.1" } ["previewType"]=> string(5) "image" } } ["events_date"]=> string(24) "2018-05-25T11:45:00.000Z" } ["form_key"]=> string(16) "H3xhipTLApQ77NfQ" }

Best Answer

not clear with your question, assuming you want to upload file in pub/media/event

try this

<?php
namespace VenderName\ModuleName\Controller\Index;

use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;

class Post extends \Magento\Framework\App\Action\Action
{
protected $_objectManager;
protected $_storeManager;
protected $_filesystem;
protected $_fileUploaderFactory;

public function __construct(
  \Magento\Framework\App\Action\Context $context,
  \Magento\Framework\ObjectManagerInterface $objectManager,
  StoreManagerInterface $storeManager, 
  \Magento\Framework\Filesystem $filesystem, 
  \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory)
{
    $this->_objectManager = $objectManager;
    $this->_storeManager = $storeManager;
    $this->_filesystem = $filesystem;
    $this->_fileUploaderFactory = $fileUploaderFactory;
    parent::__construct($context);
}

public function execute()
{
    $mediaDir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
    $mediapath = $this->_mediaBaseDirectory = rtrim($mediaDir, '/');

    $uploader = $this->_fileUploaderFactory->create(['fileId' => 'id_from_tamplatefile_of upload_control']);
    $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
    $uploader->setAllowRenameFiles(true);
    $path = $mediapath . '/events/';
    $result = $uploader->save($path);
}

}
Related Topic