JM Lontoc
JM Lontoc

Reputation: 373

Symfony 4 - Download file from project directory

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

Upvotes: 2

Views: 13176

Answers (2)

Giovani
Giovani

Reputation: 2547

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');

Upvotes: 8

Deniz Akt&#252;rk
Deniz Akt&#252;rk

Reputation: 362

maybe it can work:

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

Have you tried this?

Upvotes: 0

Related Questions