Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3059

New in Symfony 3.2: File controller helper

$
0
0
Dennis Fridrich

Contributed by
Dennis Fridrich
in #18502.

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
useSymfony\Bundle\FrameworkBundle\Controller\Controller;classBookControllerextendsController{publicfunctiondownloadAction(){$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
useSymfony\Component\HttpFoundation\ResponseHeaderBag;return$this->file($pdfPath,'sample.pdf',ResponseHeaderBag::DISPOSITION_INLINE);

In addition to file path strings, this helper also accepts File andUploadedFile instances as its first argument:

1
2
3
4
5
useSymfony\Component\HttpFoundation\File\File;$samplePdf=newFile($this->getParameter('dir.downloads').'/sample.pdf');return$this->file($samplePdf);

Be trained by Symfony experts - 2016-07-04 London - 2016-07-04 London - 2016-07-06 London

Viewing all articles
Browse latest Browse all 3059

Trending Articles