Question:

How to set different file size upload limits for different Asset Sources

Carter: 2 weeks ago

How can I set file size upload limits on a per-Asset Source basis?

I can only see how to set a global maxUploadFileSize (https://craftcms.com/docs/config-settings#maxUploadFileSize) in the general config.

I'm sure I must be missing something obvious though, as this is something that was even possible in EE1! :-) It's a common use case to have a lower limit on some upload destinations to keep clients from uploading massive files (e.g. images), and to allow a higher limit on certain upload destinations for general file downloads.

Otherwise, we will have to use a 10mb limit for everything globally (as an example), and the clients can then upload images up to that size (which can happen with high resolution images). This will waste storage space and potentially run into PHP memory issues when resizing high resolution images for the front-end. :-/

Answer:
Cameron: 2 weeks ago

You can use the Event (https://github.com/craftcms/docs/blob/master/en/updating-plugins.md#events) System from Yii/Craft and check for the file size during an upload

Event::on(
    Asset::class,
    Element::EVENT_BEFORE_SAVE,
    function(ModelEvent $modelEvent){
        /** @var Asset $model */
        $model = $modelEvent->sender;
        $tmpPath = $model->tempFilePath;
        $fileSize = filesize($tmpPath);
        if($fileSize > $someVariable){
            return false;
        }
    }
);

You can set $someVariable by a custom field in your volume $volume = Craft::$app->volumes->getVolumeById($model->volumeId); or by some config variables or in set of globals and so on