Magento, Magento 2

How to Download File Programmatically in Magento 2

How to Download File Programmatically in Magento 2

In this tutorial, Today I will explain to how to download file programmatically in Magento 2. There are some CSV files, images files etc. added in downloadable product and when we click on that it should be download file. Same functionality if we need to apply in custom page at that time, how we need to apply code for that? Let’s see the below steps for that :

You may also like this :

Steps for Download File Programmatically in Magento 2 :

1) First of all, Let’s assume that you have created simple module. Now, I added code in controller file. You just need to copy below code and paste in your controller :


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Controller\Index;

use Magento\Framework\App\Filesystem\DirectoryList;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\App\Response\Http\FileFactory
     */
    protected $fileFactory;

    /**
     * @param \Magento\Framework\App\Action\Context            $context
     * @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory
    ) {
        $this->fileFactory = $fileFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $filePath = 'media/md_product_print/logo.svg';
        $downloadName = 'logo1.svg';
        $content['type'] = 'filename';
        $content['value'] = $filePath;
        $content['rm'] = 0; // If you will set here 1 then, it will remove file from location.
        return $this->fileFactory->create($downloadName, $content, DirectoryList::PUB);
    }
}

You need to inject \Magento\Framework\App\Response\Http\FileFactory this class in your file and add execute() method your method logic.

In create() method, You need to first argument as download file name, Second argument as array of output of file and third argument as directory path from where you want to get download file.

Here, I added file path for pub/media image path. So, as directory path I added DirectoryList::PUB to get file from pub directory.

Now, Just remove generated, clean cache and execute action.

That’s it !!!

I hope this blog is easy to understand about how to download file programmatically in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged ,