Magento 2 : How to write a controller to download a file

Updated . Posted . Visible to the public.
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\Filesystem\DirectoryList;
use Magento\Framework\App\Action\Action;
use Magento\Customer\Model\Session;


class DownloadPrescription extends Action
{
    /**
     * @var FileFactory 
     */
    protected $fileFactory;
    
    /**
     * @var DirectoryList 
     */
    protected $directory;

    /**
     * @var Session 
     */
    protected $session;

    

    /**
     * DownloadPrescription constructor.
     * @param Context $context
     * @param FileFactory $fileFactory
     * @param DirectoryList $directoryList     
     * @param Session $session
     */
    public function __construct(
        Context $context,
        FileFactory $fileFactory,
        DirectoryList $directoryList,        
        Session $session
    ) {
        parent::__construct($context);

        $this->fileFactory = $fileFactory;
        $this->directory = $directoryList;        
        $this->session = $session;

    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
     * @throws \Magento\Framework\Exception\FileSystemException
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function execute()
    {
        if (!$this->session->isLoggedIn()) {
            return $this->_redirect('customer/account/login');
        }

        $id = $this->getRequest()->getParam('id');
        

        $file = $this->directory->getPath("var").$path;

        /**
         * do file download
         */
        return $this->fileFactory->create(
            'testing.pdf',
            @file_get_contents($file)
        );
    }
}
vasan
Last edit
vasan
Keywords
File, download
Posted by vasan to vasan's deck (2021-02-20 15:55)