0

As there is no native config to control the naming of assets I am trying to write a small plugin to do this. Here is what I have;

    craft()->on('assets.saveAsset', function (Event $event) {
        if ($event->params['isNewAsset']) {

            $asset = $event->params['asset'];

            // Set the filename to a variable, appending the file extension
            // $extension = $asset->getExtension();
            // $filename = strtolower($asset->filename.md5(time()).'.'.$asset->getExtension());
            $filename = strtolower($asset->filename.'.'.$asset->getExtension());

            // Rename the file on the server
            craft()->assets->renameFile($asset, $filename);

            // Set filename attribute and re-save asset
            $asset->setAttribute('filename', $filename);
            craft()->assets->storeFile($asset);
        }
    });

However, this currently results in a duplication of the extension like so; model-rendering-image.jpg.jpg
special-services.jpg.jpg

If I remove this part of the code '.'.$asset->getExtension()) then the asset isn't renamed at all.

Can't seem to get past this hurdle.

Anyone able to shed some light?

Also is there a reason that assets are not renamed to lowercase by default or why this isn't rolled in as a config option?

  • 1
    Possible duplicate of Change asset name on upload – Brad Bell Dec 1 '17 at 17:27
  • This is certainly based on that but my question is more specifically about how to remove the duplicate extension in the name. – Terry Upton Dec 1 '17 at 20:56
1

Just tested your code and it worked as you'd expect if you leave off the extra getExtension() call (the filename property already includes the extension).

$filename = strtolower($asset->filename);

If it's not saving for you with that, you've got some other error happening elsewhere.

| improve this answer | |

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.