Sometimes you need to create your own file download script in magento, and often people use their own ways to create the script and face problems in executing it, but magento2 has its own script for file download, we can easily use this script for file downloads:
<?php /** * Webkul Software. * * @category Webkul * * @author Webkul * @copyright Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ namespace Webkul\Download\Controller\Download; use Magento\Framework\App\Action\Context; /** * File download controller. */ class Index extends \Magento\Framework\App\Action\Action { /** * @var Magento\Framework\App\Response\Http\FileFactory */ protected $_downloader; /** * @var Magento\Framework\Filesystem\DirectoryList */ protected $directory; /** * @param Context $context * @param PageFactory $resultPageFactory */ public function __construct( Context $context, \Magento\Framework\App\Response\Http\FileFactory $fileFactory, \Magento\Framework\Filesystem\DirectoryList $directory ) { $this->_downloader = $fileFactory; $this->directory = $directory; parent::__construct($context); } public function execute() { $fileName = $this->getRequest()->getParam('fileName'); $file = $this->directory->getPath("media")."/FilePath/".$fileName; // do your validations /** * do file download */ return $this->_downloader->create( $fileName, @file_get_contents($file) ); } }
In the above code, this class Magento\Framework\App\Response\Http\FileFactory is used for file download, you can open this and check the parameters that can be passed to the create function, you can also pass content type in the create method, by default it is application/octet-stream.
Hope this will help you.
Thanks 🙂 .
return $this->_downloader->create(
$fileName,
[
‘type’ => ‘string’,
‘value’ => @file_get_contents($file),
‘rm’ => true
]
);