Maxime Bernard's blog

Change the filename of your uploaded file in Symfony

Hi everyone,

It’s been a long time I didn’t post. Lot of work at work and lot of work at home with my personal project. But here I am. I’m actually working on Symfony projects and I’ve been recently learning many many features that I would like to share with you. So I’ll try to keep you posted.

This one is about the filename. Say you have a form based on a generated form and a generated class. Let’s call this class File to ease understanding. This simple class looks has 3 fields: Id, Filename and Creator.

Say you want to save your file with its original name and not the random filename generated by Symfony.

Then, you just have to implement the method generateFilenameFilename($file = null) in your class.

  public function generateFilenameFilename($file = null)

  {

    if (null === $file) {

      return null;

    }

    if (file_exists($file->getpath().’/’.$file->getOriginalName())) {

       return $this->appendToName($file);

    }

    return $this->Startup->id.’/’.$file->getOriginalName();

  }

And you can add this method to handle if the filename already exists on your server.

  public function appendToName($file, $index = 1)

  {

    $newname = pathinfo($file->getOriginalName(), PATHINFO_FILENAME).’_’.$index.$file->getExtension();

    if (file_exists($file->getpath().’/’.$newname)) {

       return $this->appendToName($file, ++$index);

    } else {

       return $newname;

    }

  }

You can even add different directories in your filename: just remember to implement a getRealName() and make a basename($filename);

You’ll find many ways on internet to do this stuff such as override sfValidatedFile, as renaming in your action or even override the doSave() of your form. But, in my opinion, this way is the most simple and intuitive you can do.


  1. maximebernard posted this
To Tumblr, Love PixelUnion