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);
}
}
Example: transliterate umlauts and accents in file names
Changed in version 15.0 Breaking: #110966 - Remove UTF8filesystem and systemLocale settings
The option UTF8filesystem, which transliterated file names when it was
disabled, has been removed.
TYPO3 stores file names with their Unicode characters, so
Grüße. keeps its umlaut. The following listener replaces each
character that has an ASCII equivalent, so the file is stored as
Gruesse., and Москва. as Moskva.. Letters
without an ASCII equivalent, such as Japanese ones, stay as they are, so
東京. and 京都. keep different names. Every other
character, such as a space or an ampersand, becomes an underscore, except
dots, underscores, and hyphens.
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\EventListener;
use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Core\Charset\CharsetConverter;
use TYPO3\CMS\Core\Resource\Event\SanitizeFileNameEvent;
#[AsEventListener(
identifier: 'my-extension/transliterate-filename',
)]
final readonly class TransliterateFileNameListener
{
public function __construct(
private CharsetConverter $charsetConverter,
) {}
public function __invoke(SanitizeFileNameEvent $event): void
{
$fileName = $this->charsetConverter->utf8_char_mapping(
$event->getFileName(),
);
$event->setFileName((string)preg_replace('/[^.\p{L}\p{N}_-]/u', '_', $fileName));
}
}
SanitizeFileNameEvent API
Changed in version 14.0
The original (unsanitized) file name can now be retrieved using
Sanitize.
-
final 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.