Documents are created by the system and saved to the folder /web/downloads. I have created a view to display links which will allow a user to download the files, should the user click the links. (standard click to download feature)
I am new to Symfony2 and am getting around the whole routing/controller concept, but how would one create a link to such files while still adhering to the MVC? Does one need to set up routing with a controller or does twig have features which allow it etc.
PS: I have read questions such as How to create a download link in Symfony2? but i do not get if they did something in the routing or just added links etc.
Thank you,
Sample implementation would be,
Create a route,
download_route:
pattern: /download/{filename}
defaults: { _controller: YourBundle:Controller:download }
And then in your controller,
public function downloadAction($filename)
{
$request = $this->get('request');
$path = $this->get('kernel')->getRootDir(). "/../web/downloads/";
$content = file_get_contents($path.$filename);
$response = new Response();
//set headers
$response->headers->set('Content-Type', 'mime/type');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);
$response->setContent($content);
return $response;
}
For generating download link check Generating urls section of the doc.
Let's make a sample.
Say your project lives in /www/, so /www/web/ is the document root of your symfony2 application. Now everything you try to access that is in /www/web/ over http://server/ will show up.
/www/web/downloads/file.zip would be reachable at http://server/downloads/file.zip by default.
Just adding the path of the file to the href
attribute didn't work for me.
When clicked, it just displays the file without really downloading it.
What worked for me though is adding a download
attribute to my link which is an HTML5 attribute. Just add the attribute like so:
<a href="path/to/file" download>Download Link</a>
Upon clicking the link, it will just download the file without any server side code.
You can also assign a value to the download
attribute.
<a href="path/to/file" download="filename.txt">Download Link</a>
The value of the download
attribute will be used as the file name of the downloaded file instead of the one used while it was stored on the server.
I followed the tutorial in the Symfony website regarding file upload handling. I found it helpful when I was figuring out how to make a download link for the file. I just added a method to the Document
entity called getDownloadFileName()
which just returns the file name I want to assign to the download
attribute.
So basically, this is how I implemented it on my Symfony project's twig template
<a href="{{ asset(file.webPath) }}" download="{{ file.downloadFileName }}">
Download Link
</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With