We sacrifice by not doing any other technology, so that you get the best of Magento.

We sacrifice by not doing any other technology, so that you get the best of Magento.

    Today we are going to explain how to download the file programmatically in Magento 2.

    Here we have added controller through which we can download image based on the click or call directly.

    namespace MagemonkeysDownloadControllerIndex;
    
    use MagentoFrameworkAppFilesystemDirectoryList;
    
    class Image extends MagentoFrameworkAppActionAction
    {
        protected $fileFactory;
    
        public function __construct(
            MagentoFrameworkAppActionContext $context,
            MagentoFrameworkAppResponseHttpFileFactory $fileFactory
        ) {
            $this->fileFactory = $fileFactory;
            parent::__construct($context);
        }
    
        public function execute()
        {
            $mediafilePath = 'media/download/homeimage.jpg';
            $downloadFilenm = 'homeimage.jpg';
            $imagearr['type'] = 'mediafilePath';
            $imagearr['value'] = $filePath;
            $imagearr['rm'] = 0;
            return $this->fileFactory->create($downloadFilenm, $imagearr, DirectoryList::PUB);
        }
    }

    We can add our logic in execute() method which will help us to download homeimage.jpg by calling this action.

    field_5bfb909c5ccae

      Get a Free Quote