2

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

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

更新

有时我尝试删除上传()的调用。然而,该方法变得从未被调用过。

4

1 回答 1

-1

解决了。

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

于 2013-04-04T09:02:55.057 回答