Magento 2 Download Files

Magento 2 Download Files Script– We can create controller action script to download files in Magento2. Let us understand how we can create controller action in magento2 to download the files.

Magento 2 Download Files Programmatically Example

Create controller which extends \Magento\Backend\App\Action. Here is an example of download controller action

Magento 2 Download Files Example:

namespace Tutorialsplane\Download\Controller\Download;
use Magento\Framework\App\Action\Context;

class Index extends \Magento\Backend\App\Action 
    protected $_downloader;
    protected $_directory;
    public function __construct(
        Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Filesystem\DirectoryList $directory
    ) {
        $this->_downloader =  $fileFactory;
        $this->directory = $directory;
    public function execute()
        $fileName = 'myTextFile.csv';
        $file = $this->directory->getPath("media")."/myfolder/".$fileName;
        $content = @file_get_contents($file);
        /**Do Your Stuffs**/
        return $this->_downloader->create(


In the above example Http File Factory is used to force and download the file. You can set the file path, file name and file content that needs to be downloaded simply as in the above example.


Add Comment

📖 Read More