Reading list Switch to dark mode

    Magento2 File Download Script

    Updated 6 March 2024

    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 🙂 .

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

    Leave a Comment

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


    4 comments

  • Emanuele
  • Gomathi c
    • ashutosh srivastava (Moderator)
  • senthil
  • Back to Top

    Message Sent!

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

    Back to Home