Skip to content

How to rename uplaoded file ? #12763

Answered by wsydney76
vitalijalbu asked this question in Q&A
Discussion options

You must be logged in to vote

Used this piece of code, when we had to obfuscate filenames, maybe it helps:

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

        if (! ... skip if this file should not be renamed... .) {
            return;
        }

        $newFilename = "$asset->uid.$asset->extension";

        // This filename exists already
        if (Asset::find()
            ->folderId($asset->folderId)
            ->filename($newFilename)
            ->exists()) {
            return;
        }

        Craft::$app->assets->moveAsset($asset, $asset->folder, $newFilename);
    }
);

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@vitalijalbu
Comment options

@wsydney76
Comment options

Answer selected by brandonkelly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants