Magento2 has a built-in script for any kind of file download, we can use the below code for file downloads:
<?php
/**
* Magemonkeys.
*
* @category Magemonkeys
*
* @author Magemonkeys
* @copyright Copyright (c) 2020 Magemonkeys (https://magemonkeys.com/)
*/
namespace MagemonkeysDownloadControllerDownload;
use MagentoFrameworkAppActionContext;
/**
* file download controller.
*/
class Index extends MagentoFrameworkAppActionAction
{
/**
* @var MagentoFrameworkAppResponseHttpFileFactory
*/
protected $_downloader;
/**
* @var MagentoFrameworkFilesystemDirectoryList
*/
protected $directory;
/**
* @param Context $context
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
MagentoFrameworkAppResponseHttpFileFactory $fileFactory,
MagentoFrameworkFilesystemDirectoryList $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)
);
}
}

