symfony-2.0-logo

Snippet for quick single file upload in Symfony 2.0

This is universal snippet for models that require single file upload. Simply copy & paste into your model and change method getLogo name so instead using in twig “entity.webPath” you could simply “entity.logo”. Second thing to change is upload DIR.

Stuff to import

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;


Properties

/**
 * @Assert\Image(maxSize="6000000")
 */
private $file;

/**
 * @ORM\Column(name="file_path",type="string", length=255, nullable=true)
 */
private $filePath;

Methods

/**
 * Virtual getter that returns logo web path
 * @return string 
 */
public function getAvatar() {
  return $this->getWebPath();
}

/**
 * CHANGE UPLOAD DIR FOR YOUR NEEDS
 * 
 * @return string 
 */
private function getUploadDir() {
  return 'uploads/avatars';
}

public function getFile() {
  return $this->file;
}

public function setFile($file) {
  $this->file = $file;
}

public function getFilePath() {
  return $this->filePath;
}

public function setFilePath($filePath) {
  $this->filePath = $filePath;
}

public function getAbsolutePath() {
  return null === $this->filePath ? null : $this->getUploadRootDir() . '/' . $this->filePath;
}

public function getWebPath() {
  return null === $this->filePath ? null : $this->getUploadDir() . '/' . $this->filePath;
}

private function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
  return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}

public function upload() {
  // the file property can be empty if the field is not required
  if (null === $this->file) {
    return;
  }

  $hashName = sha1($this->file->getClientOriginalName() . $this->getId() . mt_rand(0, 99999));

  $this->filePath = $hashName . '.' . $this->file->guessExtension();

  $this->file->move($this->getUploadRootDir(), $this->getFilePath());

  unset($this->file);
}

2 thoughts on “Snippet for quick single file upload in Symfony 2.0

  1. Hi, Iam looking for feature to select the folder instead of file. How can that be done. Please do the needful. Thanks in advance. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>