New in Symfony 3.2: File controller helper
June 29, 2016 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
This is the first article of the "New in Symfony 3.2" series where we'll showcase the most relevant new features of the upcoming Symfony 3.2 version (to be published on November 2016).
The Symfony base controller is a utility class that includes several helper
methods for common controller tasks and provides direct access to the service
container. In Symfony 3.2 we added a new helper method called file()
to
simplify serving binary files.
The simplest way to use the file()
helper is to pass the path of the file to
download. The browser will force the download of this file and it will assign it
the same name as the original file:
1 2 3 4 5 6 7 8 9 10 11
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class BookController extends Controller
{
public function downloadAction()
{
$pdfPath = $this->getParameter('dir.downloads').'/sample.pdf';
return $this->file($pdfPath);
}
}
If you prefer to set a custom name for the file, use the optional second argument:
1
return $this->file($pdfPath, 'sample-of-my-book.pdf');
If you prefer to show the file contents in the browser instead of forcing its download, use the optional third argument:
1 2 3
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
return $this->file($pdfPath, 'sample.pdf', ResponseHeaderBag::DISPOSITION_INLINE);
In addition to file path strings, this helper also accepts File
and
UploadedFile
instances as its first argument:
1 2 3 4 5
use Symfony\Component\HttpFoundation\File\File;
$samplePdf = new File($this->getParameter('dir.downloads').'/sample.pdf');
return $this->file($samplePdf);
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Sweet!
Thank you Dennis for this nice little helper :)
Coooollll nice adition, now it's easier to download a file!!
Cool addition! Is it availabe as service?
This is great! And better!
This is an awesome addition, I remember writing a lot to download file with ResponseHeaderBag in 2.3 and 2.7 :)