使用symfony2上传许多文件

时间:2014-02-12 13:14:40

标签: php symfony doctrine

我想知道如何使用Symfony2和docrine2一次上传多个文件。目前,我只能上传一个文件

ImageType.php

<?php


class ImageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
  ->add('file', 'file', array(
  'attr' => array(
        'class' => 'input-sm form-control',
        "accept" => "image/*",
                    "multiple" => "multiple")
             )
  );

ImmobilierType.php

class ImmobilierType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
                    //...

        ->add('image', new ImageType(), array(
        'required' => false))
           //...

ImmobilierController.php

    /**
 * Create a new Immobilier entity.
 *
 */
public function newAction()
{
    $immobilier = new Immobilier();
    $form = $this->createForm(new ImmobilierType(), $immobilier);

    $request = $this->getRequest();

    if ($request->getMethod() == 'POST')
    {
        $form->bind($request);

        if ($form->isValid())
        {
            $em = $this->getDoctrine()->getManager();   
            $em->persist($immobilier);              
            $em->flush();

            $this->get('session')->getFlashBag()->add('info',     'Immobilier bien enregistré');

            return $this->redirect( $this->generateUrl('immobilier_show', array('id' => $immobilier->getId())));
        }
    }

    return $this->render('AgenceImmobBundle:Immobilier:new.html.twig',
    array(
        'form' => $form->createView() ,
        ));
}

Immobilier.php(实体)

    //...

   /**
* @ORM\OneToOne(targetEntity="Agence\ImmobBundle\Entity\Image", cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $image;

  //...

Image.php

//...

/**
* Image
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Agence\ImmobBundle\Entity\ImageRepository")
* @ORM\HasLifecycleCallbacks
*/
class Image
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="url", type="string", length=255)
 */
private $url;

/**
 * @var string
 *
 * @ORM\Column(name="alt", type="string", length=255)
 */
private $alt;


/**
* @Assert\File(maxSize="10M")
*/
public $file;


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

/**
 * Set url
 *
 * @param string $url
 * @return Image
 */
public function setUrl($url)
{
    $this->url = $url;

    return $this;
}

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

/**
 * Set alt
 *
 * @param string $alt
 * @return Image
 */
public function setAlt($alt)
{
    $this->alt = $alt;

    return $this;
}

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

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

if (null !== $this->url) {
  $this->tempFilename = $this->url;

  $this->url = null;
  $this->alt = null;
 }
}

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


private $tempFilename;

/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null === $this->file) {
  return;
}

$this->url = $this->file->guessExtension();

$this->alt = $this->file->getClientOriginalName();
}

/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
  return;
}

if (null !== $this->tempFilename) {
  $oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;
  if (file_exists($oldFile)) {
    unlink($oldFile);
  }
}

$this->file->move(
  $this->getUploadRootDir(), 
  $this->id.'.'.$this->url  
 );
}

/**
* @ORM\PreRemove()
*/
public function preRemoveUpload()
{
$this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}

/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if (file_exists($this->tempFilename)) {
  unlink($this->tempFilename);
 }
}

public function getUploadDir()
{
 return 'uploads/img';
}

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

public function getWebPath()
{
 return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}


 }

1 个答案:

答案 0 :(得分:0)

文件字段一次只上传一个文件。

发送多个文件的解决方案是为文件字段提供一个集合,如下所示:

   ->add("files", 'collection', array(
        'type'=>new FileType(),
        'allow_add'=>true,
        'data'=>array(new Bundle\Entity\File(),
        new Bundle\Entity\File())
    ))

字段的类型现在是一个集合(它是一个arrayCollection)而不是文件。 您现在需要调整“数据”中的实体声明以适合您的项目。

希望这会有所帮助:)