3

I want to change the filename before the file is stored, to prevent ugly, long and weird filenames uploaded by users.

I've found an example for Craft 2, but because of the changes for events I can't rebuild this for Craft 3 (Change asset name on upload)

I also tried to change it a event, no luck;

Event::on(
    Asset::class,
    Asset::EVENT_BEFORE_HANDLE_FILE,
    function(AssetEvent $event) {

        $asset = $event->asset;                         
        $filename = 'filename'.md5(time()).'.'.$asset->getExtension();
        $asset->filename = $filename;
    }
);

Apparently the filename property is read-only, so you can only change properties like the title.

Any help is appreciated!

4

Well, after searching for this for more than 2 hours, I bumped into a working solution;

Event::on(
    Elements::class,
    Elements::EVENT_AFTER_SAVE_ELEMENT,
    function(ElementEvent $event)   {

        $asset = $event->element;

        if ($event->isNew && $asset instanceof craft\elements\Asset) {
            $newFileName = 'file-'.md5(time()).'.'.$asset->getExtension();
            Craft::$app->assets->moveAsset($asset, $asset->getFolder(), $newFileName);
        }
    }
);

In case somebody needs it!

  • 1
    Lifesaver! But this didn't work 100% for me, so I changed function(ElementEvent $event) to function(Event $event) and it worked perfectly :) – Jason Mayo Nov 14 '18 at 11:21

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.