Symfony 4 - Download file from project directory

11,061

The right way to download a static file according Symfony docs is:

$response = new Symfony\Component\HttpFoundation\BinaryFileResponse($file);

And/or add headers and Content-Diposition:

$response->headers->set('Content-Type','text/plain'); $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'sample.txt');

Share:
11,061

Related videos on Youtube

JM Lontoc
Author by

JM Lontoc

Updated on June 04, 2022

Comments

  • JM Lontoc
    JM Lontoc almost 2 years

    In my public folder, I placed a .txt file to be downloaded once the user clicks on the download button.

    In my controller, I put path as a variable to be passed in the template.

    $context['path'] = '/public/sample.txt';
    

    In my twig file, I have:

    <a href="{{ path }}">Download</a>
    

    However, when I click the link, the download fails and a file is not found. Is there a simple way to make this work?

    Here is what appears when I click the link:

    enter image description here

    • DonCallisto
      DonCallisto over 5 years
      Hi JM. This question is "too generic" for have an answer. Plase, try to add more details, like (for instance) what does it means that "download fails" and this kind of useful infos. BTW take a look to this link
    • Vyctorya
      Vyctorya over 5 years
      Look at this answer stackoverflow.com/a/20658401/8411841 You need to write a controller action as your file can not be downloaded directly.