0

I want to redirect the user to an URL after downloading a file.

What I tried to do:

$this->fileFactory->create('file.pdf', $pdf);
return $this->_redirect($this->_redirect->getRefererUrl());

But it never executes the return statement.

How would I go about this problem?

1
1

try this code

<?php 
namespace Vendername\Modulename\Controller\Index;

use Magento\Framework\App\Filesystem\DirectoryList;

class Actionname name extends \Magento\Framework\App\Action\Action
{

    protected $uploaderFactory;

    protected $filesystem;

    public function __construct(
    ...................................................................
    \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
    \Magento\Framework\Filesystem $filesystem,
     ...................................................................
    ) {
        parent::__construct($context);
        $this->_fileFactory = $fileFactory;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
     }

    public function execute()
    {
    
        $name = date('m-d-Y-H-i-s');
        $filepath = 'export/export-data-' .$name. '.pdf';
        $this->directory->create('export');

        ...........................
        ...........................
        ...........................     

        $content = [];
        $content['type'] = 'filename'; // must keep filename
        $content['value'] = $filepath;
        $content['rm'] = '1'; //remove csv from var folder

        $pdffilename = 'data-import-'.$name.'.pdf';
        return $this->_fileFactory->create($pdffilename, $content, DirectoryList::VAR_DIR);
    }

}
4
  • Thanks for your comment, this code won't work in my case because after I run this line: php $this->fileFactory->create('file.pdf', $pdf); the code after it won't be executed.
    – crazynx
    Jun 15 '20 at 9:33
  • please check updated answer and Update me Jun 15 '20 at 9:57
  • It works, but not in my case. I can't declare a route to redirect to.
    – crazynx
    Jun 15 '20 at 10:44
  • it's works for me . it automatically download and close on new browser tab. if you need to redirect page you need to declare route.
    – Msquare
    Jun 15 '20 at 11:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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