Download Files in Magento 2

Written by Mahesh Makwana

Jul 25, 2021

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

Mahesh Makwana

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP