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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Form Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Rename file on upload


Go to End


7 Posts   1951 Views

Avatar
Johnny9

Community Member, 35 Posts

19 June 2014 at 11:49pm

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

Community Member, 35 Posts

30 June 2014 at 7:16pm

Is this forum dead? :D

Avatar
swaiba

Forum Moderator, 1899 Posts

30 June 2014 at 9:56pm

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

Community Member, 35 Posts

30 June 2014 at 9:59pm

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

Maybe where is method like setFolderName, just for files?

Avatar
Devlin

Community Member, 344 Posts

1 July 2014 at 2:46am

Edited: 01/07/2014 2:48am

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

Forum Moderator, 1899 Posts

18 July 2014 at 10:35pm

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

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

Avatar
Johnny9

Community Member, 35 Posts

18 July 2014 at 11:42pm

Edited: 18/07/2014 11:47pm

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 :)