2

I wrote the following code in Module.php that checks if a file size is too large during an asset upload (the file size limit and asset volume handles are defined in a globals: a table with one column the volume handle and the other column the size limit in bytes)

/* image file size limit */
        Event::on(
            Asset::class,
            Element::EVENT_BEFORE_SAVE,
            function(ModelEvent $modelEvent){
              $model = $modelEvent->sender;
              if(isset($model->volumeId) && !empty($model->volumeId)) {
                // Get the image
                $volume = Craft::$app->volumes->getVolumeById($model->volumeId);
                // Get the settings global set
                $settings = Craft::$app->globals->getSetByHandle('imageSizeLimits');
                $tmpPath = $model->tempFilePath;
                $fileSize = filesize($tmpPath);
                if( (!empty($settings->assetVolumes)) && (isset($settings->assetVolumes)) ) {
                  foreach($settings->assetVolumes as $row) {
                    $volumeHandle = $row['volumeHandle'];
                    $sizeLimit = $row['sizeLimit'];
                    if( (!empty($sizeLimit)) && (isset($sizeLimit)) && (!empty($volumeHandle)) && (isset($volumeHandle)) ) {
                      // Check if the volume should have a size limit
                      if($volume->handle == $volumeHandle){
                        if($fileSize > $sizeLimit){
                          $imgName = $model->filename;
                          if($sizeLimit >= 1000000) {
                            $limit = floor($sizeLimit/1000000); //limit in MB
                            throw new VolumeException("{$imgName} exceeds {$limit} MB limit");
                            return false;
                          } else {
                            $limit = floor($sizeLimit/1000); //limit in MB
                            throw new VolumeException("{$imgName} exceeds {$limit} KB limit");
                            return false;
                          }
                        }
                      }
                    }
                  }
                }
              }
              return;
            }
        );
        /* end image file size limit */

When uploading an asset to an entry where the asset exceeds the file size limit, the exception is thrown and an alert box appears, which is expected. But once the 'OK' button is clicked, the upload bar stays and you can no longer try to upload anything else. (screenshot below) screenshot of upload bar How to I stop the upload from hanging when an exception is thrown?

2

Rather than throwing an exception when the filesize is too large, you should be adding a validation error, which should be handled correctly.

use craft\base\Model;
use craft\elements\Asset;
use craft\events\DefineRulesEvent;
use craft\helpers\ArrayHelper;
use yii\base\Event;

Event::on(
    Asset::class,
    Model::EVENT_DEFINE_RULES,
    function(DefineRulesEvent $event) {
        /** @var Asset $asset */
        $asset = $event->sender;

        $event->rules[] = ['tempFilePath', function(string $attribute) use ($asset) {
            if (!$asset->volumeId) {
                return;
            }

            // Get the volume
            $volume = Craft::$app->volumes->getVolumeById($asset->volumeId);
            // Get the settings global set
            $settings = Craft::$app->globals->getSetByHandle('imageSizeLimits');
            // See if we have a size limit for this volume
            $volumeSettings = ArrayHelper::firstWhere($settings->assetVolumes ?? [], 'volumeHandle', $volume->handle);
            if (empty($volumeSettings['sizeLimit'])) {
                return;
            }

            // Make sure the asset is within the allowed file size
            $fileSize = filesize($asset->tempFilePath);
            if ($fileSize > $volumeSettings['sizeLimit']) {
                $formattedSizeLimit = Craft::$app->formatter->asShortSize($volumeSettings['sizeLimit'], false);
                $asset->addError($attribute, "$asset->filename exceeds $formattedSizeLimit");
            }
        }];
    }
);
2
  • no luck! Have any other suggestions?
    – berrydev
    Sep 1 at 18:57
  • @berrydev Can you elaborate? Maybe write into support@craftcms.com with your Composer files and full module code, and we can work with you from there. Sep 13 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.