Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Form Questions

Rename file on upload


Reply

7 Posts   308 Views

Avatar
Johnny9

19 June 2014 at 11:49pm Community Member, 21 Posts

Hi, i have front end form, with file input field. When I upload it, I want to change file name to some random numbers or letters (ect. 4455asdasd54.jpg).

How can I do that? Maybe someone could provide simple code example?

Avatar
Johnny9

30 June 2014 at 7:16pm Community Member, 21 Posts

Is this forum dead? :D

Avatar
swaiba

30 June 2014 at 9:56pm Forum Moderator, 1796 Posts

Is this forum dead?
no, maybe that isn't something someone can help you with :)

I'm sure you can get this by debugging and hacking the core code - not that I would advise that.

Avatar
Johnny9

30 June 2014 at 9:59pm Community Member, 21 Posts

Hi, swaiba,
I'm glad that at least someone wrote back :)

Maybe where is method like setFolderName, just for files?

Avatar
Devlin

1 July 2014 at 2:46am (Last edited: 1 July 2014 2:48am), Community Member, 215 Posts

You could create a DataExtension for File and extend the method onAfterUpload().

Something like:

class MyFileExtension extends DataExtension {
   function onAfterUpload() {
      $file = $this->owner;
      $file->Name = 'myFilename';
      $file->write();
   }
}

Not tested... but should work.

Avatar
swaiba

18 July 2014 at 10:35pm Forum Moderator, 1796 Posts

Saw this in the addons, thought it might be useful to you...

http://addons.silverstripe.org/add-ons/silverstripe/selectupload

Avatar
Johnny9

18 July 2014 at 11:42pm (Last edited: 18 July 2014 11:47pm), Community Member, 21 Posts

Hi, tried what Devlin suggested, but it didn't worked out, so my solution was:

if(!empty($data['Photo1']['name'])){
   $photo1 = File::get()->byID(Member::currentUser()->Photo1ID);
   // getting ext
   $ext1 = $photo1->getExtension();            
   $random1 = (int)substr(uniqid('', true), -7);
   $randomDate1 = $random1 + (int)time();
   $photo1->Name = 'sitename-' . $randomDate1 . $CurrentMemberID . $random1 . '.' . $ext1;
   $photo1->write();
}

it's not perfect, but it worked.

Thank you all for the help :)