Created
September 19, 2011 10:10
-
-
Save ftassi/1226254 to your computer and use it in GitHub Desktop.
Symfony File Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Porzione del controller che valida il form di upload | |
if ($form->isValid()) { | |
$em = $this->getDoctrine()->getEntityManager(); | |
$document->upload(); | |
$em->persist($document); | |
$em->flush(); | |
$this->redirect('...'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/Acme/DemoBundle/Entity/Document.php | |
namespace Acme\DemoBundle\Entity; | |
use Doctrine\ORM\Mapping as ORM; | |
use Symfony\Component\Validator\Constraints as Assert; | |
/** | |
* @ORM\Entity | |
*/ | |
class Document | |
{ | |
/** | |
* @ORM\Id | |
* @ORM\Column(type="integer") | |
* @ORM\GeneratedValue(strategy="AUTO") | |
*/ | |
public $id; | |
/** | |
* @ORM\Column(type="string", length=255) | |
* @Assert\NotBlank | |
*/ | |
public $name; | |
/** | |
* @ORM\Column(type="string", length=255, nullable=true) | |
*/ | |
public $path; | |
/** | |
* @Assert\File(maxSize="6000000") | |
*/ | |
public $file; | |
public function upload() | |
{ | |
// the file property can be empty if the field is not required | |
if (null === $this->file) { | |
return; | |
} | |
// we use the original file name here but you should | |
// sanitize it at least to avoid any security issues | |
// move takes the target directory and then the target filename to move to | |
$this->file->move($this->getUploadRootDir(), $this->file->getClientOriginalName()); | |
// set the path property to the filename where you'ved saved the file | |
$this->setPath($this->file->getClientOriginalName()); | |
// clean up the file property as you won't need it anymore | |
$this->file = null; | |
} | |
public function getAbsolutePath() | |
{ | |
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path; | |
} | |
public function getWebPath() | |
{ | |
return null === $this->path ? null : $this->getUploadDir().'/'.$this->path; | |
} | |
protected function getUploadRootDir() | |
{ | |
// the absolute directory path where uploaded documents should be saved | |
return __DIR__.'/../../../../web/'.$this->getUploadDir(); | |
} | |
protected function getUploadDir() | |
{ | |
// get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view. | |
return 'uploads/documents'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment