Reading list Switch to dark mode

    How to upload image in Magento 2

    Updated 23 February 2024

    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.

    Start your headless eCommerce
    now.
    Find out More

    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.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    3 comments

  • Bhupendra Jadeja
    • hardik
    • Birjitsinh Zala
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home