nzo / file-downloader-bundle
Symfony bundle to serve local files inline or as downloads and stream remote files to disk
Package info
github.com/NAYZO/NzoFileDownloaderBundle
Type:symfony-bundle
pkg:composer/nzo/file-downloader-bundle
Requires
- php: >=8.1
- ext-fileinfo: *
- symfony/dependency-injection: ^6.4 || ^7.0 || ^8.0
- symfony/filesystem: ^6.4 || ^7.0 || ^8.0
- symfony/framework-bundle: ^6.4 || ^7.0 || ^8.0
- symfony/http-client: ^6.4 || ^7.0 || ^8.0
- symfony/http-client-contracts: ^3.0
- symfony/http-foundation: ^6.4 || ^7.0 || ^8.0
- symfony/http-kernel: ^6.4 || ^7.0 || ^8.0
- symfony/mime: ^6.4 || ^7.0 || ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.68
- phpstan/phpstan: ^1.12 || ^2.0
- phpunit/phpunit: ^9.6
- rector/rector: ^1.2 || ^2.0
- symfony/var-dumper: ^6.4 || ^7.0 || ^8.0
Suggests
- ext-curl: Enables Symfony HttpClient's cURL transport for remote downloads
Provides
None
Conflicts
None
Replaces
None
README
A Symfony bundle that streams local files to the browser, inline or as downloads, without buffering the entire file.
It can also send a generated stream as an attachment, save a remote HTTP file to disk, or look up its media type without downloading its body.
Which version do I need?
| Your application | Bundle version | Install |
|---|---|---|
| Symfony 6.4, 7 or 8 | 5 | composer require nzo/file-downloader-bundle:^5.0 |
| Symfony 4.4 to 6.3, or PHP earlier than 8.1 | 4 | composer require nzo/file-downloader-bundle:^4.3 |
Version 5 requires PHP 8.1 or later. Use a PHP version supported by your Symfony release.
The documentation for version 4 is on the 4.x branch. Upgrading? Read UPGRADE-5.0.md before deploying.
Installation
composer require nzo/file-downloader-bundle:^5.0
If Symfony Flex does not register the bundle for you, add it to config/bundles.php:
return [ // ... Nzo\FileDownloaderBundle\NzoFileDownloaderBundle::class => ['all' => true], ];
Configuration
The bundle has no configuration options of its own. Autowire Nzo\FileDownloaderBundle\FileDownloader\FileDownloader, or reference @nzo_file_downloader in your service definitions. Relative paths are resolved under %kernel.project_dir%/public.
Remote requests use a dedicated Symfony HttpClient. They do not inherit the headers or other defaults of the application's http_client service. To set limits for remote transfers, supply a dedicated client configured with timeout (maximum idle time) and max_duration (maximum total time) as the optional second constructor argument to FileDownloader.
ext-fileinfo is required to detect local file types. ext-curl is optional.
Usage
Download a file from public/
The example serves public/reports/annual.txt under a friendlier name. Omit the second argument to keep the original filename. Register the controller as an autowired, autoconfigured service so Symfony can inject the downloader.
use Nzo\FileDownloaderBundle\FileDownloader\FileDownloader; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException; use Symfony\Component\HttpKernel\Attribute\AsController; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Routing\Attribute\Route; #[AsController] class ReportController { public function __construct(private readonly FileDownloader $downloader) { } #[Route('/reports/annual', name: 'annual_report', methods: ['GET'])] public function download(): BinaryFileResponse { try { return $this->downloader->downloadFile('reports/annual.txt', 'annual-report.txt'); } catch (FileNotFoundException $exception) { throw new NotFoundHttpException('The annual report is not available.', $exception); } } }
For a file outside public/, use downloadFileFromAbsolutePath() with a trusted path, for example /srv/reports/annual.txt. These methods return a Symfony BinaryFileResponse, which streams the file and handles range requests when Symfony prepares the response.
Local file responses use Cache-Control: no-cache, private by default. This allows private caches to store a copy, but requires revalidation before reuse. For sensitive documents, add no-store to the response before returning it:
$response = $this->downloader->downloadFileFromAbsolutePath($trustedPath); $response->headers->addCacheControlDirective('no-store'); return $response;
Display a local file inline
return $this->downloader->readFile('manuals/getting-started.pdf'); // For a file outside public/, after checking access: // return $this->downloader->readFileFromAbsolutePath('/srv/manuals/getting-started.pdf');
The bundle detects the file's media type. The browser decides whether it can display the file inline or has to download it.
Download generated content
Pass a StreamedResponse if your application generates the content instead of reading a file:
use Symfony\Component\HttpFoundation\StreamedResponse; $report = new StreamedResponse(static function (): void { echo "id,name\n42,Alice\n"; }, 200, ['Content-Type' => 'text/csv; charset=UTF-8']); return $this->downloader->downloadStreamedResponse($report, 'report.csv');
The bundle keeps the status and any existing content type. It sets application/octet-stream if none was set. For both local and streamed attachments, UTF-8 filenames are sent with an ASCII fallback.
Save a remote file to disk
Use a trusted URL and an absolute destination path in a directory that already exists:
$saved = $this->downloader->downloadFileFromUrl( 'https://files.example.test/reports/annual.csv', '/srv/imports/annual.csv', ['Accept: text/csv'], 'ReportImporter/1.0', );
The method streams an HTTP 200 response into a temporary file next to the destination. It returns true after a complete transfer replaces the destination, including for an empty file. On cancellation or a request or write failure, it returns false and leaves any existing destination untouched. Redirects are not followed.
Identify a remote file
getFileExtensionFromUrl() first checks for a known extension in the URL path. If it finds none, it sends a HEAD request and looks up the extension for the reported Content-Type. getFileTypeWithoutDownload() always uses HEAD and returns the media type without parameters. Both return null if they cannot determine a result. Some servers do not support HEAD. Neither method verifies the actual contents.
Security
- Relative paths cannot resolve outside
public/, including through symlinks. Keep directories used to serve files under application control. For private files, check the user's access before serving a trusted path outside the web root. The bundle does not perform authorization. - Use inline responses only for files you trust. The browser can execute active content such as HTML or SVG on your application's origin. Serve untrusted uploads as attachments and keep them outside the web root.
- Remote methods can contact any reachable HTTP or HTTPS host, including private hosts. Do not pass untrusted URLs or destination paths directly to the bundle. Choose URLs from trusted application configuration, restrict outbound access, and set time and storage limits appropriate to the files you import.
License
This bundle is under the MIT license. See the LICENSE file.