Reading list Switch to dark mode

    Programmatically Download File in Magento 2

    Updated 5 March 2024

    In this blog I will show you, how you can programmatically download file in Magento 2.

    Please check the below code,

    <?php
    namespace Webkul\Csv\Controller\Index;
    
    use Magento\Framework\App\Action\Action;
    use Magento\Framework\App\Action\Context;
    use Magento\Framework\App\Filesystem\DirectoryList;
    
    class GetFile extends Action
    {
        public function __construct(
            Context $context,
            \Magento\Framework\App\Response\Http\FileFactory $fileFactory
        ) {
            $this->fileFactory = $fileFactory;
            parent::__construct($context);
        }
     
        public function execute()
        {
            $filepath = 'export/customerlist.csv';
            $downloadedFileName = 'CustomerList.csv';
            $content['type'] = 'filename';
            $content['value'] = $filepath;
            $content['rm'] = 1;
            return $this->fileFactory->create($downloadedFileName, $content, DirectoryList::VAR_DIR);
        }
    }

    Here, $filepath is the path of the file under var/ folder. $downloadedFileName is the file name when it get downloaded on client side. If $content[‘rm’] is equal to 1 then the file will be deleted from server after it has been downloaded.

    If you want to know how to create a csv file then please check out the blog “How to Create a CSV file in Magento 2”.

    Please comment if you face any issue or if there is any confusion. Thanks for checking out the blog.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home