Symfony上传:无法移动文件

时间:2013-04-04 07:32:16

标签: symfony file-upload doctrine

我已经为文件上传实现了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')

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

更新

有时我尝试删除upload()的调用。然而,这种方法从未被调用过。

1 个答案:

答案 0 :(得分:0)

解决。

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