我想用 symfony2 和 doctrine 上传个人资料图片

I want to upload a profile picture with symfony2 and doctrine

在 User.php 中(实体名称是 User),我在 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(),
    ));
}

我要在哪里给出我要保存图片的路径?如何将上传的文件保存到我想要的目录中,并将目录路径保存到数据库中?

您需要在实体中创建上传方法。查看此 link 了解更多详情 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(),
    ));
}

基督徒的回答是有效的,但是我只想更具体地指出如何做所要求的。简单地做:

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

希望对您有所帮助。