Jump to:

2002 Posts in 1422 Topics by 616 members

Form Questions

SilverStripe Forums » Form Questions » Rename file on upload

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

Page: 1
Go to End
Author Topic: 196 Views
  • Johnny9
    Avatar
    Community Member
    19 Posts

    Rename file on upload Link to this post

    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?

  • Johnny9
    Avatar
    Community Member
    19 Posts

    Re: Rename file on upload Link to this post

    Is this forum dead?

  • swaiba
    Avatar
    Forum Moderator
    1784 Posts

    Re: Rename file on upload Link to this post

    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.

  • Johnny9
    Avatar
    Community Member
    19 Posts

    Re: Rename file on upload Link to this post

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

    Maybe where is method like setFolderName, just for files?

  • Devlin
    Avatar
    Community Member
    215 Posts

    Re: Rename file on upload Link to this post

    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.

  • swaiba
    Avatar
    Forum Moderator
    1784 Posts

    Re: Rename file on upload Link to this post

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

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

  • Johnny9
    Avatar
    Community Member
    19 Posts

    Re: Rename file on upload Link to this post

    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

    196 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.