Today's tutorial will guide you on how to download a file programmatically in Magento 2. There are certain file forms such as CSV files, PNG/JPG image files eccetra. When the file is allowed to be downloaded, you can download file anytime. If we want to apply the same functionality to a custom page, here is code that can be applied for it. Let us follow a certain steps:
All you need to do is copy below code and paste it in your controller.
<?php namespace MageDelight\Helloworld\Controller\Index; use Magento\Framework\App\Filesystem\DirectoryList; class Index extends \Magento\Framework\App\Action\Action { /** * @var \Magento\Framework\App\Response\Http\FileFactory */ protected $fileFactory; /** * @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory */ public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\App\Response\Http\FileFactory $fileFactory ) { $this->fileFactory = $fileFactory; parent::__construct($context); } public function execute() { $filePath = 'media/md_product_print/logo.svg'; $downloadName = 'logo1.svg'; $content['type'] = 'filename'; $content['value'] = $filePath; $content['rm'] = 0; // If you will set here 1 then, it will remove file from location. return $this->fileFactory->create($downloadName, $content, DirectoryList::PUB); } }
Then, inject this class: \Magento\Framework\App\Response\Http\FileFactory in your file and add execute() method in the method logic.
In the create() method, the first argument must be made as a download file name, the second argument as an array of the output of the file, and the third argument as a directory path from where you want to get the download file.
Here, Add file path for pub/media image path. So, as directory path add DirectoryList:: PUB to get the file from pub directory.
Now, simply clean the cache and execute the action.
That’s it !!!
We hope we covered everything. In case we missed out on something, feel free to reach us out.