Magento

Download Files in Magento 2

Written by Mahesh Makwana

Jul 25

Download Files in Magento 2

There are many times we need to allow users to download files from Magento 2 file system. Here we learn how to Download Files in Magento 2. There are many operations for files in Magento like read, write, append, create, delete, insert, update, etc. Below code is performed download any type of file in Magento 2.

<?php

namespace Dolphin\SampleDownload\Controller\Index;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\ResultFactory;

class DownloadFile extends \Magento\Framework\App\Action\Action
{
    protected $fileFactory;
    protected $_storeManager;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
    ) {
        $this->_storeManager = $storeManager;
        $this->fileFactory = $fileFactory;
        parent::__construct($context);
    }
    public function execute()
    {
        $fileName = "test.pdf"; // add your file name here
        if ($fileName) {
            $filePath = 'media/catalog/attachments/file/' . $fileName;
            $content['type'] = 'filename';// type has to be "filename"
            $content['value'] = $filePath; // path where file place
            $content['rm'] = 1; // if you add 1 then it will be delete from server after being download, otherwise add 0.
            $mediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
            $mediaUrl .= 'catalog/attachments/file/' . $fileName;
            $imageHeaders = get_headers($mediaUrl);
            if (isset($imageHeaders[0])) {
                $imageStatus = stripos($imageHeaders[0], "200 OK") ? true : false;
                if ($imageStatus) {
                    return $this->fileFactory->create($fileName, $content, DirectoryList::PUB);
                } else {
                    $this->messageManager->addError(__("File does not exist"));
                }
            } else {
                $this->messageManager->addError(__("File does not exist"));
            }
        } else {
            $this->messageManager->addError(__("Something went wrong"));
        }
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }
}

In the above code, we add one file to our Magento 2 file system at path <magetno root>/pub/media/catalog/attachments/file/test.pdf. You can also change the file path and file name from the above code. And here we also check file is exists or not by using PHP get_headers() method.

Note: Please Make sure you must be added the right file name with extension and file path where the file exists.

I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.

You also like to to read this

Written by Mahesh Makwana

Our Magento Store

Do not miss a chance to grab exciting offers on Magento Development at Dolphin Web Solution. We are providing discounts on various Magento services this season. Go and grab yours today at our Magento Store.

Multiple Wishlist for Magento 2

Multiple Wishlist for Magento 2

₹ 3106

Wallet and Reward Points for Magento 2

Wallet and Reward Points for Magento 2

₹ 9476

RMA for Magento 2

RMA for Magento 2

₹ 11865

₹ 14254
Abandoned Cart Email for Magento 2

Abandoned Cart Email for Magento 2

₹ 6291

Simple Details on Configurable Product for Magento 2

Simple Details on Configurable Product for Magento 2

₹ 7883

₹ 9476
Frequently Bought Together for Magento 2

Frequently Bought Together for Magento 2

₹ 5494

₹ 7087

Let's Start Your Project

Get free consultation for your digital product idea to turn it into reality!

Copyright © 2023 DOLPHIN WEB SOLUTION. All rights reserved.

TO TOP