BeforeFileAddedEvent
The PSR-14 event
\TYPO3\
is fired before a file is about to be added to the resource
storage /
driver.
This allows to perform custom checks to a file or restrict access to a file
before the file is added.
Example
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\Resource\EventListener;
use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Core\Resource\Event\BeforeFileAddedEvent;
use TYPO3\CMS\Core\Resource\Exception\UploadSizeException;
use TYPO3\CMS\Core\Utility\GeneralUtility;
#[AsEventListener(
identifier: 'my-extension/before-file-added',
)]
class BeforeFileAddedEventListener
{
private const MAX_UPLOAD_SIZE_FOR_PDF = 10 * 1024 * 1024;
private const MAX_UPLOAD_SIZE_FOR_ZIP = 20 * 1024 * 1024;
/**
* @throws UploadSizeException
*/
public function __invoke(BeforeFileAddedEvent $event): void
{
$uploadedFileData = $this->getUploadedFileDataFromGlobalFiles(
$event->getSourceFilePath(),
);
if ($uploadedFileData === null) {
return;
}
$uploadedFileSize = $uploadedFileData['size'] ?? 0;
$fileRefs = GeneralUtility::split_fileref(
$uploadedFileData['name'],
);
$uploadedFileExtension = $fileRefs['fileext'] ?? '';
if (
$uploadedFileExtension === 'pdf'
&& $uploadedFileSize > self::MAX_UPLOAD_SIZE_FOR_PDF
) {
throw new UploadSizeException(
'PDF files must not be larger than 10MB.',
);
}
if (
$uploadedFileExtension === 'zip'
&& $uploadedFileSize > self::MAX_UPLOAD_SIZE_FOR_ZIP
) {
throw new UploadSizeException(
'ZIP files must not be larger than 20MB.',
);
}
}
private function getUploadedFileDataFromGlobalFiles(
string $tmpName,
): ?array {
foreach ($_FILES as $uploadedFileData) {
if ($uploadedFileData['tmp_name'] === $tmpName) {
return $uploadedFileData;
}
}
return null;
}
}
New in version 13.0
The PHP attribute
\TYPO3\ has been
introduced to tag a PHP class as an event listener. Alternatively, or if you
need to be compatible with older TYPO3 versions, you can also register an
event listener via the Configuration/Services.yaml file. Switch to
an older version of this page for an example or have a look at the section
Implementing an event listener in your extension.