Tag Archives: Magento 2 Force File Download

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:

_downloader =  $fileFactory;
        $this->directory = $directory;
        parent::__construct($context);
    }
    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(
            $fileName,
            $content
        );

    }
}

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.