To upload an image in Magento, you need to write the following code inside your controller:
use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Backend\App\Action; protected $_fileUploaderFactory; public function __construct( \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory, Action\Context $context ) { $this->_fileUploaderFactory = $fileUploaderFactory; parent::__construct($context); } public function execute(){ $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploader->setAllowRenameFiles(false); $uploader->setFilesDispersion(false); $path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA) ->getAbsolutePath('images/'); $uploader->save($path); }
Here,
_fileUploaderFactory: Is an object of \Magento\MediaStorage\Model\File\UploaderFactory , which handles all the uploading process.
[‘fileId’ => ‘image’]: Where ‘image’ is name of your input type = file element.
setAllowedExtensions(): List of file extensions you allowed to upload.
setFilesDispersion(): If you set it to “false” then your file uploaded to the same path, and if you set it to “true” then it first creates two folders with first two letters of image’s name, and then upload your image inside that folder.
save(): Is used to upload and save file at the path which you passed inside it.
If you want to save the image with custom name, then you need to pass your file name as a second parameter.
Thank you for reading this article on How to upload image in Magento 2, we hope you liked it.
You can also view our wide range of ready-to-use Magento 2 extensions.
Further for any more queries, please reach out to our team via support ticket.
MagentoBackendAppActionContext $context