How to automatically rename the image files to a random string during the upload process? For example, I have an image named "big_poster.jpg" and I want it to be saved as something random, for example "2680542675157_cc7m541v_l.jpg"

I see every asset have a "Filename" and "Title" field. Would be possible to use these fields to generate a random string? Perhaps using the Randomm plugin?

  • 1
    Curiously, what's the use case for this? Oct 29 '14 at 2:49
  • I'd like this as well. I have users adding photos from the front end and it would be nice to be able to organise them automatically as I have no control over what there original files are named.
    – shorn
    Nov 2 '14 at 22:27
  • @shorn Exactly!
    – rey
    Nov 8 '14 at 22:00

Use the assets.onBeforeSaveAsset event

You could write a plugin that listens for when an asset is saved via the assets.onBeforeSaveAsset event and rename the image before it is saved to the database?

So you could have something like this in your plugins init method:

craft()->on('assets.onBeforeSaveAsset', function(Event $event) {

    // Only rename if it’s a new asset being saved
        $asset = $event->params[‘asset’];

        $asset->setAttribute(‘filename’, ‘SOME_RANDOM_STRING’);

I haven’t tested this code, but from looking at Craft’s source and the docs this should work.

Documentation about events can be found on the Craft website

  • Hi @Alec-Ritson :) If you don't mind answering a probably dumb question, should I add something in 'SOME_RANDOM_STRING'?
    – rey
    Nov 14 '14 at 22:01
  • Yes you would replace it with whatever random name you want to generate, like in your question: 2680542675157_cc7m541v_l.jpg Nov 14 '14 at 22:07
  • But that would generate a different random name for every image? Or that would do for one image only?
    – rey
    Nov 14 '14 at 22:10
  • You would just need a way of generating a unique filename for each asset that's uploaded, so you could hash the initial filename then time stamp it, or you could look at hashids for generating random hashes from id's (if there is a user id for example) it's just down to preference on how you want the filenames stored :) Nov 14 '14 at 23:13
  • I'm sorry, I'm a terrible developer >.< Would be possible to use something like this for Craft? stackoverflow.com/a/3261107
    – rey
    Nov 16 '14 at 7:36

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.