0

I am trying to download a file that is located in the /media/attachment/ location.

Downloading works with exact file size but never opened. says file format not supported for images, for pdf it says the file is corrupt.

Here is my code, please help.

'''

class Attachment extends \Magento\Framework\App\Action\Action
{
protected $_pageFactory;
protected $request;
protected $_customerSession;
protected $customerGroup;
protected $attachmentmodelFactory;
protected $_storeManager;
/**
 * @var Magento\Framework\App\Response\Http\FileFactory
 */
 protected $_downloader;
/**
 * @var Magento\Framework\Filesystem\DirectoryList
 */
protected $_directory;

/**
 * @param Context     $context
 * @param PageFactory $resultPageFactory
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\App\Request\Http $request,
    \Magento\Customer\Model\Session $session,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    CustomerGroup $customerGroup,
    \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
    \Magento\Framework\Filesystem\DirectoryList $directory,
    \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
    \PurpleCommerce\Attachment\Model\ResourceModel\Attachment\CollectionFactory $attachmentmodelFactory,
    \Magento\Framework\View\Result\PageFactory $pageFactory)
{
    $this->_pageFactory = $pageFactory;
    $this->request = $request;
    $this->customerGroup = $customerGroup;
    $this->_storeManager = $storeManager;
    $this->_downloader =  $fileFactory;
    $this->directory = $directory;
    $this->resultRawFactory      = $resultRawFactory;
    $this->attachmentmodelFactory = $attachmentmodelFactory;
    $this->_customerSession = $session;
    return parent::__construct($context);
}


public function downloadfile($currentCustCode,$visibleto,$attachment){
    // if(in_array($currentCustCode,$visibleto)){
        
        $url= $attachment[0]['icon'];
        $dir = dirname($url);
        $subdir = substr($dir, strpos($dir, 'attachment')+10);
        $fileName = basename($url);

        $file = $this->directory->getPath("media")."/attachment".$subdir.'/'.$fileName;
        
        $imageHeaders = get_headers($url);

        /**
         * do file download
         */


        return $this->_downloader->create(
            $fileName,
            @file_get_contents($file)
        );

       // also tried this with no luck

        //return $this->fileFactory->create(
        //     $fileName, 
        //     $content, 
        //     DirectoryList::PUB,
        //     'application/octet-stream'
        //  );


   }
}

'''

1 Answer 1

0

Try this

<?php
 
namespace VendoreName\ModuleName\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;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.