我想上传一张带有symfony2和doctrine的个人资料图片

时间:2015-08-06 12:06:32

标签: php symfony orm doctrine-orm doctrine

在User.php(实体名称是User)中,我在名为userPic的用户实体中有一个字段,类型为String

在文件UserType.php中,我提到了userPic,如下所示:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('userFullname')
        ->add('userName')
        ->add('userEmail')
        ->add('userPassword')
        ->add('userPic', 'file', array ('label'=>'profile Picture'))
        ->add('gender','choice',array('choices' => array('m' => 'Male', 'f' => 'Female')))

        ->add('isActive')
    ;
}

现在在控制器中我得到如下所示的表单字段

/**
 * Creates a new User entity.
 *
 */
public function createAction(Request $request)
{
    $entity = new User();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

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

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

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

我必须在哪里提供保存图片的路径?如何将上传的文件保存在我想要的目录中并将目录路径保存在数据库中?

2 个答案:

答案 0 :(得分:1)

克里斯蒂安的回答是有效的,但是我想更具体地指出如何做出要求。只需:

if ($form->isValid()) {
    $file = $form->getData()['file'];
    $file->move('/your/path/to/your/file', 'yourFileName');
    // Do the rest
    ...
}

希望这有帮助。

答案 1 :(得分:0)

您需要在实体中创建上传方法。请查看此链接以获取更多详细信息http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

public function uploadFile()
{
    // the file property can be empty if the field is not required
    if (null === $this->getFile()) {
        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->getFile()->move($this->getUploadDir(), $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;
}

/**
 * Creates a new User entity.
 *
 */
public function createAction(Request $request)
{
    $entity = new User();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

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

        // Upload file
        $entity->uploadFile();    

        $em->persist($entity);
        $em->flush();

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

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