Skip to content

Instantly share code, notes, and snippets.

@jiewmeng
Created May 7, 2012 13:54
Show Gist options
  • Save jiewmeng/2627913 to your computer and use it in GitHub Desktop.
Save jiewmeng/2627913 to your computer and use it in GitHub Desktop.
Symfony 2 Image Upload
/**
* @ORM\PrePersist
*/
public function uploadIcon() {
// proceed with upload only if isDirty
if (!$this->isDirty)
return;
// delete the old file if any
$oldIcon = APP_ROOT .'/uploads/' . $this->iconUrl;
if ($this->iconUrl != '' && file_exists($old)) {
unlink($old);
}
// guess the extension
$ext = $this->iconFile->guessExtension();
if (!$ext)
$ext = 'png';
// upload the icon (new name will be "proj_{id}.{ext}")
$newIcon = sprintf('proj_%d.%s', $this->id, $ext);
$this->iconFile->move(APP_ROOT . '/uploads/', $newIcon);
// set icon with path to icon (relative to app root)
$this->iconUrl = $newIcon;
// cleanup
unset($this->iconFile);
$this->isDirty = false;
}
@jiewmeng
Copy link
Author

jiewmeng commented May 7, 2012

In model class ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment