Serving files for download
Routes can be used to serve file downloads with the BinaryFileResponse
response object. Using the BinaryFileResponse
to serve a file for download allows you to keep the original file’s URL private or to send dynamic content as a file download.
In this recipe, we will create a route that provides a download for a PDF.
Getting started
This recipe uses a PDF file that is located in the same directory as the module. You can use any other available file type, such as a text file. A test PDF can be found on the World Wide Web Consortium website at https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf.
How to do it…
- First, we need to create the
src/Controller
directory in the module’s directory. We will put our controller class in this directory, which gives our controller class theController
namespace:mkdir -p src/Controller
- Create a file named
DownloadController.php
in theController
directory. This...