-
Notifications
You must be signed in to change notification settings - Fork 678
Closed
Labels
Description
What happened?
Description
I'm trying to limit the allowed uploaded filesize depending on the extension of the file, since not all extensions have the same max limit. But for some reason sizeInBytes
returns <span class="not-set">(not set)</span> B
instead of the size.
Does this have to do with the asset being a temporary upload instead of a normal upload? Or is there another approach to achieve the same result?
It looks like it tries to return the Bytes because is also returns a B
but not the size.
Event::on(Asset::class, Asset::EVENT_BEFORE_SAVE, function(Event $event) {
/** @var Asset $asset */
$asset = $event->sender;
$extension = $asset->getExtension();
$sizeInBytes = $asset->getFormattedSizeInBytes();
$maxSizes = [
'jpg' => 5 * 1024 * 1024, // 5MB
'pdf' => 10 * 1024 * 1024, // 10MB
'mp4' => 50 * 1024 * 1024, // 50MB
];
if (isset($maxSizes[$extension]) && $sizeInBytes > $maxSizes[$extension]) {
throw new \yii\web\HttpException(400, "The file is too large for .$extension files.");
}
});
Steps to reproduce
- Add the above code to the
modules.php
in theattachEventHandlers()
function.
Expected behavior
I expect $asset->getFormattedSizeInBytes();
to return a proper value.
Actual behavior
$asset->getFormattedSizeInBytes();
returns `(not set)
Craft CMS version
5.8.5
PHP version
8.4
Operating system and version
No response
Database type and version
No response
Image driver and version
No response