Symfony2图像文件上传

时间:2015-04-01 10:49:37

标签: doctrine

我正尝试通过表单处理图片上传,然后在我网站的其他地方显示这些图片上传。

到目前为止,我一直在查看Cookbook以及其他教程。我创建了一个实体和一个表单并且能够提交,但我不确定我是否将文件本身存储在我的数据库中或只是它的名字。

当我尝试在图像中显示我的视图资源中未找到错误的图像时。有关在Symfony上传图像的正确方法的任何建议吗?

这就是我到目前为止所拥有的。实体

<?php
namespace BlogBundle\Entity;
use Symfony\Component\HttpFoundation\File\File;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Photo
*
* 
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Upload 
{

/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
  /**
  *Image File
* @var File
* @Assert\File( maxSize = "5M",mimeTypes = {"image/jpeg", "image/gif",    "image/png", "image/tiff"}, mimeTypesMessage = "Please upload a valid Image")
  * 
  */
  private $file;
  /**
 * @ORM\Column(type="string", length=500)
 */
private $title;
/**
 * @ORM\Column(type="string", length=500)
 */
private $description;


/**
 * Image path
 *
 * @var string
 *
 * @ORM\Column(type="text", length=255, nullable=false)
 */
protected $path;


 protected function getUploadRootDir()
{
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

 protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'uploads/documents';
}

/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set title
 *
 * @param string $title
 * @return Upload
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

/**
 * Get title
 *
 * @return string 
 */
public function getTitle()
{
    return $this->title;
}

/**
 * Set description
 *
 * @param string $description
 * @return Upload
 */
public function setDescription($description)
{
    $this->description = $description;

    return $this;
}

/**
 * Get description
 *
 * @return string 
 */
public function getDescription()
{
    return $this->description;
}

/**
 * Set path
 *
 * @param string $path
 * @return Upload
 */
public function setPath($path)
{
    $this->path = $path;

    return $this;
}

/**
 * Get path
 *
 * @return string 
 */
public function getPath()
{
    return $this->path;
}

/**
 * Called before saving the entity
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
 public function preUpload()
 {   
 if (null !== $this->file) {
    // do whatever you want to generate a unique name
    $filename = sha1(uniqid(mt_rand(), true));
    $this->path = $filename.'.'.$this->file->guessExtension();
}
}

/**
 * Called before entity removal
 *
 * @ORM\PreRemove()
 */
 public function removeUpload()
 {
  if ($file = $this->getAbsolutePath()) 
  {
    unlink($file); 
   }
 }

/**
* Called after entity persistence
*
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
// The file property can be empty if the field is not required
if (null === $this->file) {
    return;
}

// 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->getFile()->getClientOriginalName()
);

// set the path property to the filename where you've saved the file
$this->path = $this->getFile()->getClientOriginalName();


// Clean up the file property as you won't need it anymore
$this->file = null;
}

/**
 * Sets file.
 *
 * @param UploadedFile $file
 *@return Upload
 */
public function setFile(File $file = null)
{
    $this->file = $file;

}

/**
 * Get file.
 *
 * @return UploadedFile
 */
public function getFile()
{
    return $this->file;
}
    }

控制器方法

/** This is the homepage for the admin area, for adding,deleting,editing of blog posts.
 * @Route("/posted/admin/upload", name="upload")
 * @Template()
 */
 public function uploadimageAction(Request $request)
 {
 $upload = new Upload();


//create checkboxtype form
$form = $this->createForm(new ImageFormType(), $upload, array(
        'action' => $this->generateUrl('upload'),
        'method' => 'POST',
  ));

$form->handleRequest($request);

if($form->isValid()){
          $em = $this->getDoctrine()->getManager();
          $upload->upload();
          $em->persist($upload);
          $em->flush();
  //   exit(\Doctrine\Common\Util\Debug::dump($post));

      return $this->render('BlogBundle:Default:success.html.twig'


            );
            ;
}
return $this->render('BlogBundle:Default:upload.html.twig',array(
          'form' =>$form->createView(),

  ));
 }

1 个答案:

答案 0 :(得分:1)

您只是将路径存储在数据库中,只有它是必需的。

使用路径可以在视图中显示文件

pd:您将文件存储在服务器中:

$this->file->move(
    $this->getUploadRootDir(),
    $this->getFile()->getClientOriginalName()
);