1

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?

rey
  • 97
  • 6

1 Answers1

2

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
if($event->params[‘isNewAsset’])
{
    $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

Alec Ritson
  • 4,529
  • 1
  • 19
  • 34
  • 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 – Alec Ritson 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 :) – Alec Ritson Nov 14 '14 at 23:13
  • I'm sorry, I'm a terrible developer >.< Would be possible to use something like this for Craft? http://stackoverflow.com/a/3261107 – rey Nov 16 '14 at 07:36