How to Create Custom Download Link in Magento 2

Magento 2 CMS is a widely suited platform for various types of online businesses.

Owing to the features it offers and capabilities of customization, the CMS is popular among the store owners. Today, I will talk about one such feature that can be developed using the below code and how a business owner can use it.

For example, default Magento 2 allows importing-exporting data on the admin side by selecting ‘Entity Type’ from System > Data Transfer > Import. It offers one link named “Download Sample File.” It automatically downloads a CSV file when you click on that link.

Now, what if you want to create custom download link in Magento 2 to allow your customers to download some sample data file or any document from the frontend? 

You can allow the visitors to download a privacy policy or product user guide or any custom file that has information they need to know.

In all such cases, you can use the below solution:

Use the below code in Index.php at app/code/Meetanshi/Extension/Controller/Download

<?php

namespace Vendore\Extension\Controller\Download;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Filesystem\DirectoryList;
use Psr\Log\LoggerInterface;

class Index extends Action
{
    protected $downloader;
    protected $logger;
    protected $directory;

    public function __construct(Context $context,
                                FileFactory $fileFactory,
                                LoggerInterface $logger,
                                DirectoryList $directory)
    {
        $this->logger = $logger;
        $this->downloader = $fileFactory;
        $this->directory = $directory;
        parent::__construct($context);
    }

    public function execute()
    {

        $fileName = $this->getRequest()->getParam('file');
        $filePath = '';

        try {
            $filePath = $this->directory->getPath("media") . '/Dir_path/' . $fileName;
        } catch (FileSystemException $e) {
            $this->logger->info($e->getMessage());
        }
        try {
            return $this->downloader->create($fileName, [
                'type' => 'filename',
                'value' => $filePath,
            ],
                \Magento\Framework\App\Filesystem\DirectoryList::MEDIA,
                'application/octet-stream');
        } catch (\Exception $e) {
            $this->logger->info($e->getMessage());
        }
        //  return true;
    }
}

Use the above code wherever you want to add a custom download link in Magento 2.

That’s all.

Also, do share the post with Magento 2 store owners via social media.

Thank you.

Table of Contents