我试图上传图片,但图片未保存在网络文件夹中。当我在实体image
中签入数据库时,我可以看到图片的名称。
AvatarType.php
->add('image', 'file', array(
'label' => 'Image',
'required' => false
))
PostController.php
public function avatarAction(Request $request)
{
$user = $this->container->get('security.context')->getToken()->getUser();
$entity = new Avatar();
$form = $this->createForm(new AvatarType(), $entity);
if ($this->get('request')->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity->setUser($user);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('avatar'));
}
}
return $this->render('FLYBookingsBundle:Post:avatar.html.twig', array('user' => $user,
'entity' => $entity,'form' => $form->createView()));
}
Avatar.php
<?php
namespace FLY\BookingsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Application\Sonata\UserBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* Avatar
*
* @ORM\Table(name="avatar")
* @ORM\HasLifecycleCallbacks
*/
class Avatar
{
/**
*
*
* @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
* @ORM\JoinColumn(onDelete="CASCADE")
* @Security("user.getId() == post.getUser()")
*/
private $user;
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/*
* @param User $user
*/
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $image
*
* @ORM\Column(name="image", type="string", length=255)
*/
private $image;
/**
* @Assert\File(
* maxSize="1M",
* mimeTypes={"image/png", "image/jpeg", "image/gif"}
* )
*/
public $imageFile;
/**
* @var text $description
*
* @ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set image
*
* @param string $image
*/
public function setImage($image)
{
$this->image = $image;
}
/**
* Get image
*
* @return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set description
*
* @param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* @return text
*/
public function getDescription()
{
return $this->description;
}
// Upload d'image
public function getFullImagePath()
{
return null === $this->image ? null : $this->getUploadRootDir().$this->image;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir().$this->getId()."/";
}
protected function getTmpUploadRootDir()
{
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../web/uploads/';
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUploadImage()
{
if (null !== $this->imageFile) {
$this->image = 'image.' .$this->imageFile->guessExtension();
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function uploadImage()
{
if (null === $this->imageFile) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
$this->imageFile->move($this->getUploadRootDir(), $this->image);
unset($this->imageFile);
}
/**
* @ORM\PostRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
}
添加
edit_profile.html.twig
<img src="{{ asset( 'uploads/brochures/' ~ entity.brochure) }}" />
user.php的
/**
* @ORM\Column(type="string")
*
* @Assert\NotBlank(message="Please, upload the product brochure as a PDF file.")
* @Assert\File(
* maxSize="3M",
* mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
* )
*/
private $brochure;
public function getBrochure()
{
return $this->brochure;
}
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
/**
* @ORM\PrePersist()
*/
public function preUpload()
{
if (null !== $this->brochure) {
// do whatever you want to generate a unique name
$this->path = uniqid().'.'.$this->brochure->guessExtension();
}
}
/**
* @ORM\PostPersist()
*/
public function upload()
{
if (null === $this->brochure) {
return;
}
$this->brochure->move($this->getUploadRootDir(), $this->brochure);
$this->brochure = null;
}
service.yml
application.brochure_uploader:
class: Application\Sonata\UserBundle\Controller\FileUploader
arguments: [ '%brochures_directory%' ]
application.doctrine_brochure_listener:
class: Application\Sonata\UserBundle\EventListener\BrochureUploadListener
arguments: [ '@application.brochure_uploader' ]
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: preUpdate }
BrochureUploadListener.php
class BrochureUploadListener
{
private $uploader;
public function __construct(FileUploader $uploader)
{
$this->uploader = $uploader;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
private function uploadFile($entity)
{
// upload only works for Product entities
if (!$entity instanceof User) {
return;
}
$file = $entity->getBrochure();
// only upload new files
if (!$file instanceof UploadedFile) {
return;
}
$fileName = $this->uploader->upload($file);
$entity->setBrochure($fileName);
}
}
FileUploader.php
class FileUploader
{
private $targetDir;
public function __construct($targetDir)
{
$this->targetDir = $targetDir;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->targetDir, $fileName);
return $fileName;
}
}