Magento 2 How To Download File From Custom Path

In Magento 2, if you want to download the file from any path, you can use the below code snippet for file downloads.
Just for your information, the class Magento\Framework\App\Response\Http\FileFactory is used for file download. You can check the parameters that can be passed to the create method, you can also pass content type in the create method, by default it is application/octet-stream.

<?php
namespace Magemeta\File\Controller\Download;

use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\Filesystem\DirectoryList;

/**
 * File download controller
 */
class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var FileFactory
     */
    protected $downloader;

    /**
     * @var DirectoryList
     */
    protected $directory;

    /**
     * @param Context     $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(Context $context, FileFactory $fileFactory, DirectoryList $directory)
    {
        $this->downloader = $fileFactory;
        $this->directory = $directory;
        parent::__construct($context);
    }

    public function execute()
    {
        $fileName = $this->getRequest()
            ->getParam('fileName');
        $file = $this
            ->directory
            ->getPath("var") . "/FilePath/" . $fileName;
        // do your validations
        
        /**
         * do file download
         */
        return $this
            ->downloader
            ->create($fileName, @file_get_contents($file));
    }
}

Hope this help you!

Leave a Reply