2013-04-04 163 views
2

我已经实现了文件上传的symfony表单。表单类型是像下面Symfony上传:无法移动文件

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
    ->add('file', 'file', array(
     'required' => false, 
     'label' => 'Upload Photo', 
     'label_attr' => array('class' => 'control-label') 

    )); 
} 

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    $resolver->setDefaults(array(
     'data_class' => '<path to entity>' 
     )); 
} 

实体是像下面

//start upload config 
/** 
* @Assert\File(maxSize="5M") 
*/ 
private $file; 

/** 
* @var string $photo 
* 
* @ORM\Column(type="string", nullable=true) 
*/ 
private $photo; 


/** 
* @ORM\PrePersist() 
* @ORM\PreUpdate() 
*/ 
public function preUpload() 
{ 
    //handle upload file 
    if (null !== $this->file) { 
     $filename = $this->getUsername(); 
     // var_dump($filename); 
     $this->photo = $filename.'.'.$this->file->guessExtension(); 
    }   
} 

/** 
* @ORM\PostPersist() 
* @ORM\PostUpdate() 
*/ 
public function upload() 
{ 
    //handle upload file gambar 
    if (null === $this->file) { 
     return; 
    } else { 
     $this->file->move($this->getUploadRootDir(), $this->photo); 
     unset($this->file); 
    } 
} 

/** 
* @ORM\PostRemove() 
*/ 
public function removeUpload() 
{ 
    //handle upload file gambar 
    if ($file = $this->getAbsolutePath()) { 
     unlink($file); 
    } 
} 

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

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

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

/** 
* Image upload 
*/ 
protected function getUploadDir() 
{ 
    return 'foto'; 
} 

和动作里面就像下面

$entityItem->upload(); 
$this->em()->persist($entityItem); 
$this->em()->flush(); 

我尝试提交表单数据,然后我得到像下面的错误

Could not move the file "/tmp/phpS3TVed" to 
"<path to my entity folder>/../../../../web/foto" 
(move_uploaded_file(): Unable to move '/tmp/phpS3TVed' to 
'path to my entity folder>/../../../../web/foto') 

这个错误的可能原因是什么,我该如何摆脱它?谢谢。

UPDATE

有时我试着删除上传的()调用。然而,这个方法从来没有被称为。

+0

您是否检查过权限? (即HTTP服务器运行的用户需要写入该目录的权限) – ManseUK 2013-04-04 07:42:00

+0

即使我已将web/foto文件夹更改为777 .. – mrkhv 2013-04-04 07:44:26

+0

拥有者为www-data – mrkhv 2013-04-04 07:44:52

回答

0

已解决。

它不需要删除upload()的调用。即使我也应该添加调用preUpload()以使其工作。

+1

你能重新说一句吗? – crmpicco 2014-07-16 16:35:05