Menu Close
    Searching for an experienced eCommerce & Marketplace Development Company ?

    how to upload image in magento2

    To upload an image in magento, you need to write 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.

    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    3 comments

  • Bhupendra Jadeja
    $context variable does not have correct path it should be
    MagentoBackendAppActionContext $context
    • hardik
      where put this code ?
    • Birjitsinh Zala
      thanx bhupendra jadeja
  • Back to Top