SanitizeFileNameEvent
The PSR-14 event
\TYPO3\ is
fired when a file name is sanitized. Event listeners can modify the sanitized
file name in order to apply custom naming conventions (for example, replacing
whitespace with hyphens for SEO-friendly file names).
Example: Sanitize a file name with hyphens instead of underscores
The following listener uses the original (unsanitized) file name to replace whitespace with hyphens and assigns the result as sanitized file name.
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\EventListener;
use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Core\Resource\Event\SanitizeFileNameEvent;
#[AsEventListener(
identifier: 'my-extension/seo-friendly-filename',
)]
final readonly class SeoFriendlyFileNameListener
{
public function __invoke(SanitizeFileNameEvent $event): void
{
$originalFileName = $event->getOriginalFileName();
if (!str_contains($originalFileName, ' ')) {
return;
}
// Apply custom logic based on the original file name
$customFileName = str_replace(' ', '-', $originalFileName);
$event->setFileName($customFileName);
}
}
SanitizeFileNameEvent API
Changed in version 14.0
The original (unsanitized) file name can now be retrieved using
Sanitize.
- class SanitizeFileNameEvent
-
- Fully qualified name
-
\TYPO3\
CMS\ Core\ Resource\ Event\ Sanitize File Name Event
This event is fired after a file name has been sanitized and before a file is added to FAL. Listeners can use this event to modify the file name, and name the file according to naming conventions of a specific project.